gpt4 book ai didi

php - 将 MYSQL 查询从 for 循环中取出

转载 作者:行者123 更新时间:2023-11-29 22:32:08 25 4
gpt4 key购买 nike

我正在尝试编写一个查询,而不使用任何类型的循环来从数据库中获取值。我有一个数组 $guest_list_guest_ids 存储了我想要提取的所有 id。

不太确定如何在没有循环的情况下完成此操作,每次我都会根据我正在解析的 ID 更改查询。

    $query = 'SELECT * FROM guest_list_guests' . implode(',', $guest_list_guest_ids);
echo $query;

非常感谢任何帮助或意见。

最佳答案

这假设您正在使用 PDO,但应该适用于 MySQLi:

// the frame of the query we're going to prepare
$query_frame = 'SELECT * FROM guest_list_guests WHERE id IN (%s);'

// generate a placeholder string, one for each element in the array of ids
$placeholders = implode(',', array_fill(0, count($guest_list_guest_ids), '?'));

// make the query string, eg: SELECT * FROM guest_list_guests WHERE id IN (?,?,?,?,?);
$query = sprintf($query_frame, $placeholders);

// prepare
$stmt = $dbh->prepare($query);

// execute
$stmt->execute($guest_list_guest_ids);

// get results
var_dump($stmt->fetchAll(PDO::FETCH_ASSOC));

关于php - 将 MYSQL 查询从 for 循环中取出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29711588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com