mysqli bind_param for array of strings
I need to bind an array of values to WHERE IN(?)
clause. How can I do that?
This works:
$mysqli = new mysqli("localhost", "root", "root", "db");
if(!$mysqli || $mysqli->connect_errno)
{
return;
}
$query_str= "SELECT name FROM table WHERE city IN ('Nashville','Knoxville')";
$query_prepared = $mysqli->stmt_init();
if($query_prepared && $query_prepared->prepare($query_str))
{
$query_prepared->execute();
But this I cannot get to work with a bind_param like this:
$query_str= "SELECT name FROM table WHERE city IN (?)";
$query_prepared = $mysqli->stmt_init();
if($query_prepared && $query_prepared->prepare($query_str))
{
$cities= explode(",", $_GET['cities']);
$str_get_cities= "'".implode("','", $get_cities)."'"; // This equals 'Nashville','Knoxville'
$query_prepared->bind_param("s", $cities);
$query_prepared->execute();
What am I doing wrong?
I've also tried call_user_func_array
, but can't seem to get the correct syntax.
Solution 1:
The task is a bit elaborate but doable. I'll take the explanation from my article Mysqli prepared statement with multiple values for IN clause:
- First of all we will need to create a string with as many
?
marks as many elements are in your array. For this we would usestr_repeat()
function which comes very handy for the purpose.- Then this string with comma separated question marks have to be added to the query. Although it's a variable, in this case it is safe as it contains only constant values
- then this query must be prepared just like any other query
- then we will need to create a string with types to be used with bind_param(). Note that there is usually no reason to use different types for the bound variables - mysql will happily accept them all as strings. There are edge cases, but extremely rare. For the everyday use you can always keep it simple and use "s" for the everything.
str_repeat()
is again to the rescue.- then we need to bind our array values to the statement. Unfortunately, you cannot just write it as a single variable, like this
$stmt->bind_param("s", $array)
, only scalar variables are allowed inbind_param()
. Luckily, there is an argument unpacking operator that does exactly what we need - sends an array of values into a function as though it's a set of distinct variables!- the rest is as usual - execute the query, get the result and fetch your data!
So the correct example code would be
$array = ['Nashville','Knoxville']; // our array
$in = str_repeat('?,', count($array) - 1) . '?'; // placeholders
$sql = "SELECT name FROM table WHERE city IN ($in)"; // sql
$stmt = $mysqli->prepare($sql); // prepare
$types = str_repeat('s', count($array)); //types
$stmt->bind_param($types, ...$array); // bind array at once
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$data = $result->fetch_all(MYSQLI_ASSOC); // fetch the data
Although this code is rather big, it is incomparably smaller than any other plausible solution offered in this topic so far.
Solution 2:
You can not bind two variables with one question mark
!
For every variable you bind you need one question mark
"bind_param" checks each variable whether it matches the requirements. afterwards the string value is placed between quotes.
This will not work.
"SELECT name FROM table WHERE city IN (?)"; ( becomes too )
$q_prepared->bind_param("s", $cities);
"SELECT name FROM table WHERE city IN ('city1,city2,city3,city4')";
must be.
"SELECT name FROM table WHERE city IN (?,?,?,?)"; ( becomes too )
$q_prepared->bind_param("ssss", $city1,$city2,$city3,$city4);
"SELECT name FROM table WHERE city IN ('city1','city2','city3','city4')";
$query_prepared->bind_param
quotes string params one by one.
And the number of variables and length of string types must match the parameters in the statement.
$query_str= "SELECT name FROM table WHERE city IN ('Nashville','Knoxville')";
will become
$query_str= "SELECT name FROM table WHERE city IN (?,?)";
now bind_param
must be
bind_param("ss",$arg1,$arg2)
with this
$query_str= "SELECT name FROM table WHERE city IN (?)";
and bind_param
with
bind_param("s",$cities)
you get
$query_str= "SELECT name FROM table WHERE city IN ('Nashville,Knoxville')";
That's why an array not works .
The only solution for this fact is call_user_func_array
if you init a statement, following is unnecessary
$query_prepared = $mysqli->stmt_init();
if($query_prepared && $query_prepared->prepare($query_str)) {
This is correct
$query_prepared = $mysqli->stmt_init();
if($query_prepared->prepare($query_str)) {
if you don't want to use call_user_func_array
and you have only a small count of arguments
you can do it with the following code.
[...]
$cities= explode(",", $_GET['cities']);
if (count($cities)>3) { echo "too many arguments"; }
else
{
$count = count($cities);
$SetIn = "(";
for($i = 0; $i < $count; ++$i) {
$code.='s';
if ($i>0) {$SetIn.=",?";} else {$SetIn.="?";}
}
$SetIn.=")";
$query_str= "SELECT name FROM table WHERE city IN ".$SetIn;
// with 2 arguments $query_str will look like
// SELECT name FROM table WHERE city IN (?,?)
$query_prepared = $mysqli->stmt_init();
if($query_prepared->prepare($query_str))
{
if ($count==1) { $query_prepared->bind_param($code, $cities[0]);}
if ($count==2) { $query_prepared->bind_param($code, $cities[0],$cities[1]);}
if ($count==3) { $query_prepared->bind_param($code, $cities[0],$cities[1],$cities[2]);
// with 2 arguments $query_prepared->bind_param() will look like
// $query_prepared->bind_param("ss",$cities[0],$cities[1])
}
$query_prepared->execute();
}
[...]
}
I would suggest you try it with call_user_func_array
to reach.
look for the solution of nick9v
mysqli-stmt.bind-param
Solution 3:
use call_user_func_array like this:
$stmt = $mysqli->prepare("INSERT INTO t_file_result VALUES(?,?,?,?)");
$id = '1111';
$type = 2;
$result = 1;
$path = '/root';
$param = array('siis', &$id, &$type, &$result, &$path);
call_user_func_array(array($stmt, 'bind_param'), $param);
$stmt->execute();
printf("%d row inserted. \n", $stmt->effected_rows);
$stmt->close;