1

I have a database, and I want to get the names of multiple users in the same query by passing in an array of user_ids. Sadly, I cannot get this to work.

I have this query:

$stmt = $this->db->prepare('SELECT name FROM users WHERE user_id=?');

Where the parameter is an array:

$stmt->bind_param('i', $user_ids);

The user_ids array looks like this {1, 2}. Basically, I want to get the name of user 1 and user 2, without having to query the database more than one time.

When I have this code, I only seem to get the name of the first user, not the others:

$stmt->bind_result($name);
while ($stmt->fetch()) {
    array_push($names, $name);
}

Keep in mind that I have initialized $names like this $names = array();

How could I solve this?

Any help would be appreciated!

1 Answer 1

1

You should use IN statement like this :

<?php
//Your array
$user_ids= array(1, 2);

$inQuery = implode(',', array_fill(0, count($ids), '?'));

$db = new PDO(...);
$stmt = $db->prepare('SELECT name FROM users WHERE user_id IN(' . $inQuery . ')');

// bindvalue is 1-indexed, so $k+1
foreach ($user_ids as $k => $id)
    $stmt->bindValue(($k+1), $id);

$stmt->execute();

Inspired by Can I bind an array to an IN() condition?


From the PHP docs

<?php
/* Execute a prepared statement using an array of values for an IN clause */
$params = array(1, 21, 63, 171);
/* Create a string for the parameter placeholders filled to the number of params */
$place_holders = implode(',', array_fill(0, count($params), '?'));

/*
    This prepares the statement with enough unnamed placeholders for every value
    in our $params array. The values of the $params array are then bound to the
    placeholders in the prepared statement when the statement is executed.
    This is not the same thing as using PDOStatement::bindParam() since this
    requires a reference to the variable. PDOStatement::execute() only binds
    by value instead.
*/
$sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)");
$sth->execute($params);
?>
Sign up to request clarification or add additional context in comments.

3 Comments

You don't have to bind the params with the foreach, You can just use $stmt->execute($user_ids);
When I bind the parameters in $stmt->execute($user_ids) I get this error mysqli_stmt::execute() expects exactly 0 parameters, 1 given
@Alekplay, try the approach first and echo $inQuery, you should see "?,?" to declare that 2 parameters are expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.