MySQLi Bind Param with an array for IN

不问归期 提交于 2019-12-27 12:29:57

问题


I am trying to pass an array to $stmt->bind_param for as 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't get it to work for the life of me. Any thoughts? The above code is just a sample.


回答1:


This is a scenario where doing it this way is inappropriate. You're constructing actual SQL (that's what the commas and quotes are), and passing it in as a parameter. It's basically evaluating to value3 IN ('...') where ... is the entirety of $values.

Also that's a good call about the quotes. MySQL uses single quotes.

You'll need to either build the SQL using string concatenation alone, or use more than one parameter.

EDIT

As an example:

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



回答2:


Went through some info (also see: https://stackoverflow.com/a/13253440/165330 ).

It can but SHOULD NOT be done.

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 );


来源:https://stackoverflow.com/questions/6053239/mysqli-bind-param-with-an-array-for-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!