How to use mysqli bind_param dynamically [duplicat

2019-08-10 03:35发布

问题:

This question already has an answer here:

  • Bind multiple parameters into mysqli query 1 answer

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?

回答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);
}


标签: php mysqli