How can I pass an array of PDO parameters yet still specify their types?

Solution 1:

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.

See as well PDO MySQL: Use PDO::ATTR_EMULATE_PREPARES or not?

Solution 2:

As stated in the documentation for PDOStatement::execute:

input_parameters

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!