MySQLi Bind Param with Array for IN

I am trying to pass an array to $stmt->bind_param for an IN variable. How can i do this?

 $values = array('a','b','c','d'); $values = '"' . implode('","', $values) . '"'; $stmt->prepare('SELECT value1, value2 FROM table1 WHERE value3 IN (?)'); $stmt->bind_param('s', $values); 

I can not make it work for life. Any thoughts? The above code is just a sample.

+3
source share
2 answers

This is the scenario when this is done inappropriately. You build the actual SQL (what the commas and quotation marks are), and passing it as a parameter. It basically evaluates value3 IN ('...') , where ... is the completeness of $values .

Also, this is a good call about quotes. MySQL uses single quotes.

You will need to either build SQL using only string concatenation, or use several parameters.

EDIT

As an example:

 $values = array('a','b','c','d'); $values = "'" . implode("','", $values) . "'"; $stmt->prepare('SELECT value1, value2 FROM table1 WHERE value3 IN (' . $values . ')'); 
+1
source

Went through some information (also see: fooobar.com/questions/1239866 / ... ).

He can, but DO NOT .

To do this, dynamic variables would be used to provide automatic reference variables and with call_user_func_array to provide a dynamic number of arguments to the inverse of $ 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 ); 
+2
source

Source: https://habr.com/ru/post/1239852/


All Articles