I try to make a specific MySQL query work with PDO unnamed placeholders, and I suspect the problem might have something to do with the ‘ ‘ around the third question mark, but I just can’t figure it out.
I get the exception:
‘Invalid parameter number: number of bound variables does not match number of tokens’
Here’s the relevant parts of the function, try-catch and the like removed for ease of reading. Function is called with $column and $mytype containing simple alphanumeric strings that worked fine with the earlier pure MySQL code, before I changed it to PDO-MySQL, so they should be ok.
define('SQL_TABLE', 'mytable');
function listThem($column, $mytype) {
# These lines succeed
$databaseHandle = new PDO('mysql:host=' . SQL_HOST . ';dbname=' . SQL_DATABASE, SQL_USER, SQL_PASSWORD);
$databaseHandle->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
# The following three lines cast the exception
$input = array(SQL_TABLE, $column, $mytype);
$statementHandle = $databaseHandle->prepare('SELECT *, ((100 * likes) / (dislikes + 1)) '
. "AS rating FROM ? WHERE ? REGEXP '?' ORDER BY rating DESC;");
$statementHandle->execute($input);
# . . . more code here
}
You can’t bind table or field names as arguments using prepared statements. Parameter binding is only for values.
You will need to build those into the string. Just make sure you filter the values properly.
Also, you should not need to use ‘?’, bound arguments take care of this.