0
// 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 循环在嵌套循环之后退出是否有特殊原因?

4

1 回答 1

2

是的。您需要再次运行查询,因为每次调用时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++;
    }
}

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

于 2012-08-31T15:17:53.333 回答