为什么我的容器在循环时只循环第一项


Why is my container while loop only cycling the first item?

// current session id
$sid = session_id();
// get current cart session
$sql = "SELECT * FROM tbl_cart WHERE ct_session_id =  '$sid'";
$result = dbQuery($sql);
// get all the items in the car category
$query = "SELECT pd_id FROM tbl_product WHERE cat_id ='28'";
$r = dbQuery($query);
//Cycle through the cart and compare each cart item to the cars to determine
  if the cart contains a car in it.
         while($cart = dbFetchAssoc($result)){
    while($product = dbFetchAssoc($r)){
        echo $cart['pd_id'] . " - ";
        echo $product['pd_id']. "<br>";
    }
}

dbFetchAssoc(( 是一个自定义数据库层,基本上是 (mysql_fetch_assoc(。

我试图从查询中获取行并使用该信息进行比较。上面带有 echo 语句的代码只是出于调试目的而回显。while 循环在嵌套循环后退出是否有特殊原因?

是的。您需要再次运行查询,因为每次调用dbFetchAssoc($r)时,您都会前进该游标。

$sql = "SELECT * FROM tbl_cart WHERE ct_session_id =  '$sid'";
$result = dbQuery($sql);
// get all the items in the car category
$query = "SELECT pd_id FROM tbl_product WHERE cat_id ='28'";
while($cart = dbFetchAssoc($result)){
    $r = dbQuery($query);
    while($product = dbFetchAssoc($r)){
        echo $cart['pd_id'] . " - ";
        echo $product['pd_id']. "<br>";
    }
}

这是一个优化版本,不会对数据库造成太大影响。但是,它特定于此特定问题,如果查询集特别大,则同样是一个糟糕的选择 - 它会遇到内存问题而不是速度问题。

$sql = "SELECT * FROM tbl_cart WHERE ct_session_id =  '$sid'";
$result = dbQuery($sql);
// get all the items in the car category
$query = "SELECT pd_id FROM tbl_product WHERE cat_id ='28'";
$r = dbQuery($query);
// cache the product results into an array
$products = Array();
while($product = dbFetchAssoc($r)){
    $products[] = $product['pd_id']
}
while($cart = dbFetchAssoc($result)){
    $index = 0;
    while($product = dbFetchAssoc($r)){
        echo $cart['pd_id'] . " - ";
        echo $product[$index]. "<br>";
        $index++;
    }
}

我还没有测试过第二个代码,但这个想法应该足够清楚。