问题描述
我确实知道PDO不支持在一条语句中执行多个查询.我一直在Google搜索,发现很少有关于PDO_MYSQL和PDO_MYSQLND的帖子.
I do know that PDO does not support multiple queries getting executed in one statement. I've been Googleing and found few posts talking about PDO_MYSQL and PDO_MYSQLND.
来自: 使用PDO和Zend Framework防止SQL注入(2010年6月; Julian)
From: Protection against SQL Injection using PDO and Zend Framework (June 2010; by Julian)
似乎PDO_MYSQL和PDO_MYSQLND确实提供了对多个查询的支持,但是我无法找到有关它们的更多信息.这些项目被中止了吗?现在有什么方法可以使用PDO运行多个查询.
It seems like PDO_MYSQL and PDO_MYSQLND do provide support for multiple queries, but I am not able to find more information about them. Were these projects discontinued? Is there any way now to run multiple queries using PDO.
推荐答案
据我所知,PDO_MYSQLND
在PHP 5.3中替换了PDO_MYSQL
.令人困惑的是该名称仍然是PDO_MYSQL
.因此,现在ND是MySQL + PDO的默认驱动程序.
As I know, PDO_MYSQLND
replaced PDO_MYSQL
in PHP 5.3. Confusing part is that name is still PDO_MYSQL
. So now ND is default driver for MySQL+PDO.
总体而言,一次需要执行多个查询:
Overall, to execute multiple queries at once you need:
- PHP 5.3 +
- mysqlnd
- 模拟的准备好的语句.确保将
PDO::ATTR_EMULATE_PREPARES
设置为1
(默认值).另外,您可以避免使用准备好的语句,而直接使用$pdo->exec
.
- PHP 5.3+
- mysqlnd
- Emulated prepared statements. Make sure
PDO::ATTR_EMULATE_PREPARES
is set to1
(default). Alternatively you can avoid using prepared statements and use$pdo->exec
directly.
使用执行程序
$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');
";
try {
$db->exec($sql);
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
使用语句
$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', 'coupe');
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";
try {
$stmt = $db->prepare($sql);
$stmt->execute();
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
注释:
使用模拟的准备好的语句时,请确保已在 DSN (自5.3.6起可用).否则,如果使用某种奇数编码,则可能会有少量的SQL注入.
A note:
When using emulated prepared statements, make sure you have set proper encoding (that reflects actual data encoding) in DSN (available since 5.3.6). Otherwise there can be a slight possibility for SQL injection if some odd encoding is used.
这篇关于PDO支持多个查询(PDO_MYSQL,PDO_MYSQLND)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!