// 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循环在嵌套循环之后退出?
答案 0 :(得分: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++;
}
}
我没有测试过第二个代码,但这个想法应该足够清楚了。