How to use mysqli bind_param dynamically

I have a mysqli query whose where clause is generated in a for loop. So parameters are not known before runtime.

How can i use mysqli bind_param method in this case?

Can i use it in the for loop to bind parameters one by one?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Yes it’s possible and very simple with php5.6, first you need know how many paraments str_repeat(), count() can you help and the unpacking operator (...) too, so this way is possible make binds dynimic.

$params = [10, 50, 51, 99];
$types = str_repeat('i',count($params));

$stmt = $mysqli->prepare("SELECT * FROM t WHERE id IN (?,?,?,?)");
$stmt->bind_param($types, ...$params);
if(!$stmt->excute()){
    echo mysqli_error($con);
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply