Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 213
Ben Dowling Avatar asked May 10 '10 11:05

Ben Dowling


2 Answers

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]);
like image 162
tpunt Avatar answered Nov 03 '22 01:11

tpunt


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.

like image 24
nuqqsa Avatar answered Nov 02 '22 23:11

nuqqsa