Hi all,
I'm trying to create a prepared dynamic select statement using PDO, and it appears to me that I've got the right number of variables to parameters.
The input:
$var1 is not null
$var2 is not null
$var3 is not null
$var4 is not null
$var5 is null
The code:
//**** Begin building the query statement. ****//
$buildSTMT = "SELECT * FROM Table1 WHERE ";
$bindArray = array(); //**** Create an empty array to add to, for the execute statement, when variables are found.
if ($var1 != "") {
$buildSTMT .= "Col1 = ? ";
$bindArray[] = $var1;
}
if ($var2 != "") {
$buildSTMT .= "AND Col2 = ?";
$bindArray[] = $var2;
}
if ($var3 != "") {
$buildSTMT .= " AND Col3 = ?";
$bindArray[] = $var3;
}
if ($var4 != "") {
$buildSTMT .= " AND Col4 = ?";
$bindArray[] = $var4;
}
if ($var5 != "") {
$buildSTMT .= " AND Col5 = ?";
$bindArray[] = $var5;
}
$stringOfParms = implode (", ", $bindArray);
echo "bind array count: ".count($bindArray)."<p>"; //output shows 4.
echo "string: ".$stringOfParms."<p>"; //string echos 4 items separated by commas "string: apple, banana, carrot, dragonfruit"
echo "built: ".$buildSTMT."<p>"; //echos "built: SELECT * FROM Table1 WHERE Col1 = ? AND Col2 = ? AND Col3 = ? AND Col4 = ?
$stmt = $connection->prepare($buildSTMT);
$stmt->execute(array($stringOfParms)); //This is line #118 the error is occuring on.
The error:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in [blah] on line 118
Why this error?
b.t.w. I'm trying to replicate Example #3 here: http://www.php.net/manual/en/pdostatement.execute.php
(which doesn't show a "bind" step).