简体   繁体   English

PDO多个SELECT语句

[英]PDO multiple SELECT statements

How can i do multiple select statements in one file? 如何在一个文件中执行多个选择语句? For example i have a list of products - i then want to get the stock level's for each of the products. 例如,我有一个产品列表-然后,我想获取每个产品的库存水平。 However, it only ever returns the first product, not any other additional products. 但是,它只会返回第一个产品,而不返回其他任何产品。

$query = $db->query("SELECT * FROM `products` ORDER BY `productName` ASC"); 

    while ($row = $query->fetch(PDO::FETCH_ASSOC)){
    $productId = stripslashes($row['productId']);
    $productName = stripslashes($row['productName']);


    echo "<b>".$productName."</b><br />";


    $query = $db->query("SELECT * FROM `stock` WHERE `productId` = $productId"); 

    while ($row = $query->fetch(PDO::FETCH_ASSOC)){
        $stockId = stripslashes($row['stockId']);
        $stockFilename = stripslashes($row['stockFilename']);

    }
    echo "Stock level= " . $query-> rowCount();

}

Because your second $query is overwriting the first. 因为您的第二个$ query会覆盖第一个。 Rename the second to $query2 (and change the the $query variables to $query2 beneath it). 将第二个重命名为$ query2(并将$ query变量更改为其下方的$ query2)。 And change $row to $row2 并将$ row更改为$ row2

By the way, you can also change your first query into a join to eliminate the second query alltogether. 顺便说一句,您也可以将第一个查询更改为联接,以完全消除第二个查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM