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 L开发者_Python百科astName
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?
Your $sVal
is not an array, it's just a simple string, so when you write array($sVal)
, the execute()
sees only one value.
You need to explode() your $sVal
string to become an array:
// clean up the unnecessary single quotes and spaces
$value = str_replace(array("'", ", "), array("", ","), $value);
// make the array of the values
$value = explode(',', $value);
$stmt->execute($value);
The problem is that execute
accepts an array of parameters, with each parameter having its own key. Passing a SQL-like, comma-separated string will not work, and even if it did, it would render PDO useless.
This is wrong:
$sVal = "'tom', 'lastname', '12345', 'Diego', 'CA'";
This is how it is supposed to be done:
$sVal = array('tom', 'lastname', '12345', 'Diego', 'CA');
Per example, if you are receiving data from a form in POST, it would be:
$sVal = array(
$_POST['firstname'],
$_POST['lastname'],
$_POST['zipcode'],
$_POST['city'],
$_POST['state'],
);
$stmt->execute($sVal);
精彩评论