开发者

Can PHP's PDO be limited to a single query?

开发者 https://www.devze.com 2022-12-29 23:13 出处:网络
PHP\'s PDO 开发者_高级运维allows multiple querys to be executed at once, either via the query() method or as a prepared statement. Both of the following examples work:

PHP's PDO 开发者_高级运维allows multiple querys to be executed at once, either via the query() method or as a prepared statement. Both of the following examples work:

// Two SQL queries
$query = "SELECT * FROM table; DROP table;"

// Execute via query()
$pdo->query($query);

// Execute via prepared statement
$stmt = $pdo->prepare($query);
$stmt->execute();

Is there any way to limit PDO to a single query at a time, much like the mysql_query() function is?


This is a more up-to-date answer to this question.

The old way of preventing multi query execution was to disable emulated prepares, however this was only applicable to the PDO::prepare() method. In newer versions of PHP (>= 5.5.21 and >= 5.6.5), a new constant has been introduced to disable this multi query execution in both PDO::prepare() and PDO::query(). (Constants aren't usually added in patch versions, but this was done due to the severity of a Drupal SQL injection attack brought about by this capability).

The new constant is PDO::MYSQL_ATTR_MULTI_STATEMENTS and must be set on object creation (as the fourth argument to the PDO constructor) - setting it on a pre-existing object with PDO::setAttribute() will not work.

$pdo = new PDO('mysql:host=_;dbname=_', '', '', [PDO::MYSQL_ATTR_MULTI_STATEMENTS => false]);


Mmm, there's a way of achieving this by disabling the emulation of prepared statements in PDO to make it use the native mysql API instead (multi-querying is not supported in server-side prepared statements):

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

However, one of the drawbacks of this option is that the query cache is lost.

0

精彩评论

暂无评论...
验证码 换一张
取 消