I often create functions when code is duplicated several times. In this instance, I'm building SQL queries and binding the parameters afterwards. The query works if I dont try to bind inside a function, but the code is so much cleaner looking with the function.
Here's the code without the function (working):
if(!empty($param_steamid) && ($param_steamid != ""))
{
$stmt->bindValue(":param_steamid", '%'.$param_steamid.'%', PDO::PARAM_STR);
}
if(!empty($param_name) && ($param_name != ""))
{
$stmt->bindValue(":param_name", '%'.$param_name.'%', PDO::PARAM_STR);
}
if(!empty($param_lastclientip) && ($param_lastclientip != ""))
{
$stmt->bindValue(":param_lastclientip", '%'.$param_lastclientip.'%', PDO::PARAM_STR);
}
if(!empty($param_match) && ($param_match != ""))
{
$stmt->bindValue(":param_match", $param_match, PDO::PARAM_INT);
}
$stmt->bindValue(":startpgnum", $start_from, PDO::PARAM_INT);
Here's the code using the function and the function:
SQLBindParam($stmt, $param_steamid, "param_steamid", true);
SQLBindParam($stmt, $param_name, "param_name", true);
SQLBindParam($stmt, $param_lastclientip, "param_lastclientip", true);
SQLBindParam($stmt, $param_match, "param_match");
SQLBindParam($stmt, $start_from, "startpgnum");
function SQLBindParam(&$stmt, &$variable, $paramname, $bStringInput = false)
{
if(empty($variable) || ($variable == ""))
{
return;
}
if($bStringInput == true)
{
$stmt->bindValue(':'.$paramname, '%'.$variable.'%', PDO::PARAM_STR);
}
else
{
$stmt->bindValue(':'.$paramname, $variable, PDO::PARAM_INT);
}
return;
}
When using the function, I get the following error:
Error: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound
Notes: The where statement has similar checks for if the variables are empty/nullstring, so the # params will not be mismatched due to that check.
I passed $stmt and $variable by reference (& in front of parameter).
Any idea why the function isnt binding the parameters?
"0" (as a string) is evaluated as empty but != "". As an integer, both evaluate the same.
Solution: One of the parameters was not being bound because it was 0 (non-string) and wasnt passing the checks. It had nothing to do with it being in a function, as Ghost pointed out. Additionally, instead of empty(), I should have been using isset().
Here was my testing:
Output:
I changed the function to the following:
And edited the call for it on the last one to be: