foreach和之后的while循环



我目前有一个查询,获取数据,然后运行另一个查询。然后回显第二个查询的结果。我想做的是把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 */
}

如何将回行移出foreach循环?

try

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

需要做的是将第二个查询的结果存储到一个数组中。然后,您可以将回显语句移出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'];
    }
}

相关内容

  • 没有找到相关文章

最新更新