PHP Loop如果存在则不选择

时间:2017-04-27 13:57:37

标签: php mysql sql while-loop

我想问这是否可行?通过选择项目名称并将项目作为股票计数,并在第二个循环中选择该项目,因为它已在第一个循环中被选中

我有这个表产品

category,       name,     barcode
vegetables      apple     101010101
vegetables      apple     010101010
meat            chicken   202020202
我有2股苹果,1条是鸡肉

继承我的代码

$sql = "SELECT * FROM products";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)){ 
     $stock_query = "SELECT * FROM products WHERE name = '".$row['name']."' LIMIT 1";
     $stock_res = mysqli_query($con,$stock_query);
       while($stock_row = mysqli_fetch_assoc($stock_res)) {
           $stocks_count = "SELECT * FROM products WHERE name = '".$stock_row['item_name']."' AND category = '".$stock_row['category']."'";
           $stock_count_res = mysqli_query($con,$stocks_count);
           $stock_available = mysqli_num_rows($stock_count_res);
           echo $stocks_available; //output here is 2
           echo $stock_row['category'].'<br/>';         
           echo $stock_row['name'].'<br/>';
  }
}

输出

循环1

2(作为蔬菜苹果库存)

蔬菜

苹果

循环2

2(作为蔬菜苹果库存)

蔬菜

苹果

循环3

1(作为肉鸡库存)

我怎样才能避免第二次循环?

我不是黑客做SQL注入我有尊严。我建立自己的系统。 一切都从头开始。

1 个答案:

答案 0 :(得分:0)

试试这段代码,它可能对您有帮助。

$sql = "SELECT distinct a.name, (SELECT distinct b.category FROM products b
WHERE b.name=a.name) as 'category', (select count(c.name) from products c where c.name=a.name) as 'count' FROM products a";
$res = mysqli_query($con,$sql);
$rows=[];
while($row = mysqli_fetch_assoc($res)){ 
    echo "Name: " . $row["name"] . "<br/>";
    echo "Category: " . $row["category"] . "<br/>";
    echo "Count: " . $row["count"] . "<br/><br/>";
}

答案未针对各种情况进行测试。请在项目中针对各种情况进行测试。 将来开始使用准备好的语句,这些都非常简单和棒极了。 mysqli函数已被弃用。 一切顺利!