Câu hỏi phỏng vấn PHP
Câu hỏi

What is the difference between PDO's query() vs execute() ?

Câu trả lời

Certainly! Understanding the difference between PDO::query() and PDO::execute() is crucial for working with databases in PHP. Here's a detailed explanation:

PDO::query()

  • Purpose: The query() method is used to execute an SQL statement directly and returns a result set as a PDOStatement object.
  • Usage: It is typically used for SQL statements that do not require any parameters, such as SELECT, SHOW, or DESCRIBE.
  • Return Value: It returns a PDOStatement object on success or false on failure.
  • Example:
    php Copy
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
    $stmt = $pdo->query('SELECT * FROM users');
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
    }

PDO::execute()

  • Purpose: The execute() method is used to execute a prepared statement. It is called on a PDOStatement object that has been prepared using the prepare() method.
  • Usage: It is used for SQL statements that require parameters, providing a secure way to execute SQL queries with user input, thus preventing SQL injection.
  • Return Value: It returns true on success or false on failure.
  • Example:
    php Copy
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
    $stmt = $pdo->pre...
middle

middle

Gợi ý câu hỏi phỏng vấn

entry

What is the return type of a function that doesn't return anything?

middle

What are some of the big changes PHP has gone through in the past few years?

junior

In PHP, objects are they passed by value or by reference?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào