我目前有一个查询,它获取数据,然后运行另一个查询。然后我回应第二个查询的结果。我想做的是将回声移到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 */
}
如何将回声线移出foreach循环?
答案 0 :(得分:0)
尝试
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;
答案 1 :(得分:0)
您需要做的是将第二个查询的结果存储到数组中。然后你可以将回显移出for循环并在你的新数组上运行一个循环,如下所示:
$ids = 2,3;
$id = explode(",",$ids);
$barcode = $results = 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)){
$results[] = $row;
//$name = $row['name'];
//$img = $row['image'];
//$desc = $row['desc'];
//echo $name.$img.$desc;
}
/*ending here*/
foreach($results as $row) {
echo $row['name'] . $row['image'] . $row['desc'];
}
}