gpt4 book ai didi

php - 使用 PDO 检索存储在数据库中的数组

转载 作者:行者123 更新时间:2023-11-29 14:06:09 24 4
gpt4 key购买 nike

我有一个数组:productid = [1,2]。现在我想使用这部分代码从产品表中获取数据:

$sql = 'SELECT name FROM product WHERE id=:id';
$s = $pdo->prepare($sql);
foreach($productid as $id)
{
$s->bindValue(':id', $id);
$s->execute();
}

当我返回如下名称时:

foreach($s as $row)
{
$name[] = array(
'name' => $row['name']
);
}

我只得到了第二个id的产品名称,但没有得到两个名称。有什么问题吗?

最佳答案

I just got the product name of second id and didn't get both names. What's the problem?

你必须将你的 $name[] = $row['name']; (是的,这是正确的符号)代码放在 foreach 循环中,以及实际的代码获取数据。

您还可以形成一个类似于 IN (?,?,?,?)IN() 语句,并在一个查询中运行它。像这样的东西(未经测试):

$in   = trim(str_repeat('?,',count($productid)).",");
$sql = "SELECT name FROM product WHERE id IN ($id)";
$stmt = $db->prepare($sql);
$stmt->execute($productid);
$name = $stmt->fetchAll();

关于php - 使用 PDO 检索存储在数据库中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14316350/

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