gpt4 book ai didi

PHP foreach 和之后的 while 循环

转载 作者:行者123 更新时间:2023-11-30 00:33:49 24 4
gpt4 key购买 nike

我当前有一个查询,该查询获取数据然后运行另一个查询。然后我回显第二个查询的结果。我想做的是将 echo 移到 foreach 循环之外,但我不知道该怎么做。

$ids = 2,3;
$id = explode(",",$ids);

$barcode = array();

foreach($id as $value) {
$sql_query = $db->prepare("SELECT barcode FROM product WHERE id=:value");
$sql_query->bindParam(":value", $value);
$sql_query->execute();
$row = $sql_query->fetch(PDO::FETCH_ASSOC);
$barcode = $row['barcode'];


/* I want to move this part starting from here outside the foreach */

$sql_select_all = $db->prepare("SELECT * FROM inventory WHERE barcode=:barcode");
$sql_select_all->bindParam(":barcode", $barcode);
$sql_select_all->execute();
while($row = $sql_select_all->(PDO::FETCH_ASSOC)){

$name = $row['name'];
$img = $row['image'];
$desc = $row['desc'];

echo $name.$img.$desc;
}
/* ending here */

}

如何将 echo 行移出 foreach 循环?

最佳答案

尝试

foreach($id as $value){
$sql_query = $db->prepare("SELECT barcode FROM product WHERE id=:value");
$sql_query->bindParam(":value", $value);
$sql_query->execute();
$row = $sql_query->fetch(PDO::FETCH_ASSOC);
// make array with the entry
$barcode[] = '"'.$row['barcode'].'"';
}
// after foreach we explode the array and add comma ,
$barcode = explode(',',$barcode)

// using mysql ( [IN][1] ) query instead of ( = )
$sql_select_all = $db->prepare("SELECT * FROM inventory WHERE barcode in ($barcode)'");
$sql_select_all->bindParam(":barcode", $barcode);
$sql_select_all->execute();
while($row = $sql_select_all->(PDO::FETCH_ASSOC)){

$name = $row['name'];
$img = $row['image'];
$desc = $row['desc'];

echo $name.$img.$desc;

using IN() Function

关于PHP foreach 和之后的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22329574/

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