Passing multiple values as parameter to mysql query

假装没事ソ 提交于 2021-02-10 22:14:12

问题


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:


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


来源:https://stackoverflow.com/questions/22891713/passing-multiple-values-as-parameter-to-mysql-query

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