7

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?

Ben Dowling
  • 17,187
  • 8
  • 87
  • 103

2 Answers2

10

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]);
tpunt
  • 2,552
  • 1
  • 12
  • 18
  • I didn't find anything about PDO::MYSQL_ATTR_MULTI_STATEMENTS in PHP documentation. but I tried it and it works; – Samer Ata May 08 '16 at 20:20
  • I wasn't aware that it hadn't been document yet. I've added it to [MySQL's constants page](http://php.net/manual/en/ref.pdo-mysql.php) - it should be viewable in a couple of hours. – tpunt May 08 '16 at 20:43
7

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.

nuqqsa
  • 4,511
  • 1
  • 25
  • 30
  • 1
    "Beginning with 5.1.17, prepared statements use the query cache under certain conditions" - http://dev.mysql.com/doc/refman/5.1/en/query-cache-operation.html – VolkerK May 10 '10 at 14:12
  • There's no way to prevent it via the query() method though? – Ben Dowling May 11 '10 at 15:02
  • Not that I know, unless you use some custom code to previously filter the query string. – nuqqsa May 11 '10 at 15:24