$sql = "SELECT * FROM table WHERE id LIKE CONCAT('%', :id, '%')
LIMIT :limit1, :limit2";

I want to still use the array input like this:


Otherwise I cannot reuse the same method for executing my queries.

At the same time, the :limit1 and :limit2 doesn’t work unless it is put in like this:

$stmt->bindParam(':limit1', $limit1, PDO::PARAM_INT);

I tried to do both but it doesn’t execute with the bindParams:

$stmt->bindParam(':limit2', $limit2, PDO::PARAM_INT);

What is the way around it?

I thought I could extend PDOStatement and add a new method “bindLimit” or something but I can’t figure out what internal method PDO uses to bind parameters to a variable.


If you turn off the default setting of PDO::ATTR_EMULATE_PREPARES, then it will work. I just found out that that setting is on by default for mysql, which means you never actually use prepared statements, php internally creates dynamic sql for you, quoting the values for you and replacing the placeholders. Ya, a major wtf.

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare($sql);
$stmt->execute(array(5)); //works!

The prepares are emulated by default because of performance reasons.



As stated in the documentation for PDOStatement::execute:


An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.

For the most part, this goes entirely unnoticed as MySQL’s implicit type conversion handles the rest (but it can cause some undesirable behaviour if MySQL is using a particularly weird connection character set, as converting strings of numbers back to their numeric value might not give the expected result).

In your case, MySQL is attempting to execute a LIMIT clause that has string arguments. Whilst it could attempt to resolve that using its implicit type conversion, as it does everywhere else a string appears where an integer should be, it simply doesn’t bother and runs off crying instead.

So, you need to tell PDO that these particular parameters are integers. Since even PHP doesn’t know what type its variables are, I believe the only way to do that is to directly bind them with either PDOStatement::bindParam or PDOStatement::bindValue as you are doing (although it isn’t strictly necessary to specify the $data_type argument as a simple (int) cast of the $variable gives PHP’s otherwise clueless type system enough to work with).

As far as the internal method PDO uses to bind parameters to a variable goes, take a look at really_register_bound_param() (unsurprisingly not exposed to PHP, so you’ll be having lots of fun in C).

Good luck!


Why bind limit values when they’re not user input?

$start = 0;
$limit = 20;
$sql = "SELECT * FROM table WHERE id LIKE CONCAT('%', :id, '%')
    LIMIT $start, $limit";

Even if $start and $limit are determined from user input, say from a $_GET, you can test the value with is_int().