我正在尝试从2个表中获取行。第一个查询有效。但第二个没有。这是我的代码:
echo '<table width="100%">';
echo '<tr><td>Product</td><td>Quantity</td><td>Price</td><td>Remove</td></tr>';
foreach ($_SESSION['cart'] as $key => $cartproduct) {
list($productid, $productquantity) = split("'|", $cartproduct, 2);
global $db;
$result = $db->prepare('SELECT name FROM products WHERE ID= :ID LIMIT 1; SELECT price FROM prices WHERE productid = :ID AND quantity = :quantity LIMIT 1');
$result->bindParam(':ID', $productid);
$result->bindParam(':quantity', $productquantity);
$result->execute();
$row = $result->fetch();
if($result->RowCount() == 1){
echo '<tr><td>' . $row['name'] . '</td><td>' . $productquantity . '</td><td>' . $row['price'] . '</td><td><a href="?page=cart&removeproduct=' . $key . '">Remove</a></td></tr>'; //LINE15
}else{
unset($_SESSION['cart'][$key]);
}
}
echo '</table>';
行名称来自products表,名称price来自prices表。这是我得到的错误:
注意:未定义的索引:第15行/var/www/html/design2/pages/cart.php中的价格
我确信这个查询是有效的。有人能告诉我我做错了什么吗?
由于查询的结构方式,您正在接收未定义的索引。您有:
SELECT name FROM products WHERE ID= :ID LIMIT 1; SELECT price FROM prices WHERE productid = :ID AND quantity = :quantity LIMIT 1
它的结构是返回2个结果集。你可以在这里获得第一个结果集:
$row = $result->fetch();
但随后您尝试访问结果集中不存在的$row['price']。该结果集只是第一个SELECT的结果。如果您只是var_dump($row)并查看结果集的样子,就可以看到这一点。
看起来你可以组合你的查询,这样你就可以得到一个结果集:
SELECT p.name, pp.price FROM products p
INNER JOIN prices pp ON p.ID = pp.productid
WHERE p.ID= :ID AND pp.quantity = :quantity
LIMIT 1;
如果不能将查询合并为一个查询,那么应该迭代结果集并访问相关的$row索引。这看起来像:
while($row = $result->fetch()) {
if(isset($row['name'])) {
//do something
} else if(isset($row['price'])) {
//do something else
}
}
需要考虑的一些事项:
- 您可能需要一个LEFT JOIN而不是INNER JOIN。这取决于产品是否总是在价格表
- 我不确定你想用什么来实现限制1。您可能需要考虑并通过订购--除非它真的你在结果中返回哪条记录并不重要
- 在拆分$cartproduct后,您应该考虑测试变量$productid和$productquantity,以验证它们是否具有您想要的值。如果一个是空的/空白的怎么办
- 在尝试访问特定索引处的结果数组之前,应该先测试结果
例如:
if(isset($row['name']) && isset($row['price'])) {
//echo your results
} else {
//return an error
}