I have a PDO prepared statement in which the bound variables are prepared dynamically (they can vary from call to call) in an advanced search function on our site.
I know the actual SQL call is correct but for some reason I am getting the following error when trying to pass my string variable into the prepared statement:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I have had this error before and am very familiar with the normal resolution steps. However, my circumstances are quite strange. With the following sample code:
$columns = "FirstName, LastName, ID, City, State";
$sWhere = "WHERE (FirstName LIKE ? AND LastName
LIKE ? AND ID LIKE ? AND City
LIKE ? AND State LIKE ?)";
$sVal = "'tom', 'lastname', '12345', 'Diego', 'CA'";
$sql = "SELECT ".$columns." FROM table ".$sWhere;
$stmt = $db->prepare($sql);
$stmt->execute(array($sVal));
where $sVal can range from 'firstname', 'lastname'.... to over 12 variables. Changing the number of variables has the same result. The complete statement is:
SELECT FirstName, LastName, ID, City, State
FROM table
WHERE (FirstName LIKE ? AND LastName
LIKE ? AND ID LIKE ? AND City
LIKE ? AND State LIKE ?)
When I run my query as is, the error above is returned. When I thought I did in fact have an incorrect number of variables, I ran an ECHO on my $value statement and found they did match.
As a secondary test, I took the output from the echo of $value and plugged directly back into the execute array:
$stmt->execute(array('tom', 'lastname', '12345', 'Diego', 'CA'));
This works with any issue at all.
It does not affect my question but I also placed % symbols within my $sVal variable for correctness:
$sVal="'%tom%', '%lastname%', '%12345%', '%Diego%', '%CA%'";
It makes ZERO sense to me that the echo'd output of the SAME variable would work but the variable itself would not. Any ideas?
$value?