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

我怕爱的太早我们不能终老 提交于 2019-12-06 01:39:01

问题


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?


回答1:


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]);



回答2:


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.



来源:https://stackoverflow.com/questions/2802298/can-phps-pdo-be-limited-to-a-single-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!