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

senior

What does yield mean in PHP?

junior

What is the difference between single-quoted and double-quoted strings in PHP?

entry

How can you pass a variable by reference?

Bình luận

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

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