php - PDO 支持多个查询(PDO_MYSQL、PDO_MYSQLND)

标签 php mysql pdo

我确实知道 PDO 不支持在一条语句中执行多个查询。我一直在 Google 上搜索,发现很少有讨论 PDO_MYSQL 和 PDO_MYSQLND 的帖子。

PDO_MySQL is a more dangerous application than any other traditional MySQL applications. Traditional MySQL allows only a single SQL query. In PDO_MySQL there is no such limitation, but you risk to be injected with multiple queries.

来自:Protection against SQL Injection using PDO and Zend Framework (June 2010; by Julian)

似乎 PDO_MYSQL 和 PDO_MYSQLND 确实提供了对多个查询的支持,但我无法找到有关它们的更多信息。这些项目被终止了吗?现在有没有办法使用 PDO 运行多个查询。

最佳答案

据我所知,PDO_MYSQLND 在 PHP 5.3 中取代了 PDO_MYSQL。令人困惑的是,名称仍然是 PDO_MYSQL。所以现在ND是MySQL+PDO的默认驱动。

总的来说,要一次执行多个查询,您需要:

  • PHP 5.3+
  • mysqlnd
  • 模拟准备好的语句。确保 PDO::ATTR_EMULATE_PREPARES 设置为 1(默认)。或者,您可以避免使用准备好的语句并直接使用 $pdo->exec

使用执行

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works regardless of statements emulation
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);

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

$db->exec($sql);

使用语句

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

$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"]
);
<小时/>

注意:

使用模拟准备语句时,请确保您已在 DSN 中设置正确的编码(反射(reflect)实际数据编码) (自 5.3.6 起可用)。否则there can be a slight possibility for SQL injection if some odd encoding is used .

关于php - PDO 支持多个查询(PDO_MYSQL、PDO_MYSQLND),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56662046/

相关文章:

php - 仅将 <、>、&、 ' and "转换为 XML?

PHP PDO。查询正确时的错误号 '00000'

php - 使用计数返回数组中的差异

php - 如何将文本文件插入到数据库表mysql

cron - 为什么包含 php mail() 的第五个参数时 cron 作业无法发送电子邮件?

mysql - 如何在网站中实现消息功能

java - JDBCConnectionException 有时会出现 spring 数据和 amazon RDS

php - 在 PHP 中从远程服务器检索文件时处理延迟

mysql - 如何使用 HeidiSQL 导出一小部分数据(完整结构)

php - 执行 PDO 语句的更好方法