MySQLi Bind Param with an array for IN [duplicate]

It can but SHOULD NOT be done, as it is code that is hard to maintain (read, understand, debug, change).

A way to do it would use dynamic variables to provide auto-referencable variables and using call_user_func_array to supply a dynamic amount of arguments to the callback/method $stmt->bind_param().

<?php
$values = array('a','b','c','d');

$s = substr( str_repeat( ' , ?' , count( $values ) ) , 2 );
$stmt->prepare('SELECT value1, value2 FROM table1 WHERE value3 IN (' . $s . ')');
# OR array_map in case of different datatypes
$typeDefintions = str_repeat( 's' , count( $values ) );
$params = array( $typeDefinitions );
foreach ( $values as $k => $v ) {
    ${ 'varvar' . $k } = $v;
    $params[] = &${ 'varvar' . $k };# provide references
}
call_user_func_array( array( $stmt , 'bind_param' ) , $params );

Leave a Comment