Viewed   241 times

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.



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.


As an example:

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

call_user_func_array "Call a callback with an array of parameters"

call_user_func_array(array($stmt, "bind_param"), array_merge(array($type), $params));

should do the job

UPDATE: you have also to change your params array:

$params = array(&$firstName, &$lastName, &$address, &$postcode, &$email, &$password);

as mysqli_stmt::bind_param expects the second and the following parameters by reference.

EDIT: Your query seems to be wrong. Maybe you have less fields than you have variables there. Do:

"INSERT INTO Users (field1, field2, field3, field4, field5, field6) VALUES (?, ?, ?, ?, ?, ?)"

where you replace the name of the fields by the correct names

Friday, December 2, 2022

In my case, as shown on the update part of the question, I think arrays have better performance than mysql databases.

Array usage showed 10 times faster response even when I search through the cells to find desired values in a row. Even good indexing of the table couldn't beat the array functionality and speed.

Tuesday, December 13, 2022

You have to use a loop to get them all at once:

function resultToArray($result) {
    $rows = array();
    while($row = $result->fetch_assoc()) {
        $rows[] = $row;
    return $rows;

// Usage
$query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
$result = $mysqli->query($query);
$rows = resultToArray($result);
var_dump($rows); // Array of rows
Saturday, December 3, 2022

Just change it to var instead of let where you declare point. let is a constant.

Monday, October 10, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :