Home > Backend Development > PHP Tutorial > Does PDO_MYSQL/PDO_MYSQLND Support Multiple Queries in a Single Statement?

Does PDO_MYSQL/PDO_MYSQLND Support Multiple Queries in a Single Statement?

Linda Hamilton
Release: 2024-12-26 09:33:10
Original
670 people have browsed it

Does PDO_MYSQL/PDO_MYSQLND Support Multiple Queries in a Single Statement?

PDO Support for Multiple Queries (PDO_MYSQL, PDO_MYSQLND)

Original Question:

Despite being aware of PDO's lack of support for executing multiple queries in a single statement, concerns have been raised regarding the availability of support for such functionality in PDO_MYSQL and PDO_MYSQLND.

Answer:

Understanding PDO_MYSQL and PDO_MYSQLND:

PDO_MYSQL was depreciated and replaced by PDO_MYSQLND in PHP 5.3. However, the name remains PDO_MYSQL, making it the default driver for MySQL PDO.

Executing Multiple Queries Using PDO:

To execute multiple queries at once, you require the following:

  • PHP 5.3 or higher
  • MySQLND
  • Emulated prepared statements (PDO::ATTR_EMULATE_PREPARES set to 1, which is the default for MySQL)

Using exec:

$sql = "
DELETE FROM car;
INSERT INTO car(name, type) VALUES ('car1', 'coupe');
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$db->exec($sql);
Copy after login

Note: This method is limited to SQL containing constant values.

Using Statements:

$sql = "
DELETE FROM car;
INSERT INTO car(name, type) VALUES (:car1, :type1);
INSERT INTO car(name, type) VALUES (:car2, :type2);
";

$stmt = $db->prepare($sql);
$stmt->execute(
    ["car1" => "brand1", "type1" => "coupe", "car2" => "brand2", "type2" => "coupe"]
);
Copy after login

Loop Over Query Results:

Always remember to loop over query results after executing the statement to check for errors or collect the results.

Note on Emulated Prepared Statements:

  • Ensure proper encoding is set in the DSN to avoid potential SQL injection risks.
  • Emulate prepared statements may introduce a slight performance penalty.

The above is the detailed content of Does PDO_MYSQL/PDO_MYSQLND Support Multiple Queries in a Single Statement?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template