Home >Database >Mysql Tutorial >How Can I Execute Multiple Queries in a Single PDO Statement with PDO_MYSQL or PDO_MYSQLND?
While PDO typically does not allow multiple queries in a single statement, certain extensions provide this functionality:
PDO_MYSQLND replaced PDO_MYSQL in PHP 5.3. It serves as the default driver for MySQL PDO. This extension supports executing multiple queries simultaneously, provided the following conditions are met:
Using exec
For simple queries with constant values, you can use the exec() method:
$db = new PDO(...); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0); $sql = "..."; $db->exec($sql);
Using Statements
For queries with variable data, use prepared statements:
$db = new PDO(...); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1); $sql = "..."; $stmt = $db->prepare($sql); $stmt->execute([...]);
Remember to loop over the query results to check for errors or collect data.
When using emulated prepared statements, ensure the correct encoding is specified in the DSN (available in PHP 5.3.6 and later). Incorrect encoding may introduce a minor risk of SQL injection with unusual character sets.
The above is the detailed content of How Can I Execute Multiple Queries in a Single PDO Statement with PDO_MYSQL or PDO_MYSQLND?. For more information, please follow other related articles on the PHP Chinese website!