我想检查购物车表中是否存在product_id
,是否存在定义变量$class = 'show'
这是我的代码:
$article = $db->query("
SELECT
b.price as price,
b.shop_id as shop_id,
c.image as image,
c.name as name,
a.id as id
FROM products AS a
INNER JOIN prices AS b ON a.ean = b.sku
INNER JOIN shops as c on b.shop_id = c.id
WHERE a.id = '$product_id'
");
while ($data = $article->fetch_object()) {
$price = $data->price;
$price2 = $data->price;
$price = number_format($price, 2, ',', '');
$shop_id = $data->shop_id;
$logo = $data->image;
$name = $data->name;
//some html code here
}
现在我不知道如何检查购物车表中是否存在该产品。在两个表中,uniqe是product_id
答案 0 :(得分:2)
我为此目的使用LEFT JOIN
(请注意CASE WHEN .. THEN ..
部分)。它与cart表连接并选择一个名为exists_in_cart
的列,如果产品存在于购物车中,则值为1,否则为0):
$article = $db->query("
SELECT
b.price as price,
b.shop_id as shop_id,
c.image as image,
c.name as name,
a.id as id,
CASE WHEN cart.product_id IS NULL THEN 0 ELSE 1 END as exists_in_cart
FROM products AS a
INNER JOIN prices AS b ON a.ean = b.sku
INNER JOIN shops as c on b.shop_id = c.id
LEFT JOIN cart on a.id = cart.product_id
WHERE a.id = '$product_id'
");
如果产品存在于购物车中,您将获得1或者否则为0:
$productInCart = $data->exists_in_cart == 1 ? TRUE : FALSE;
if ($productInCart) {
$class = 'show';
}
else {
// ...
}
答案 1 :(得分:1)
检查是否返回了任何行,如果有,请设置变量。
if($article->num_rows) {
$class = "show";
}
或者,检查属性是否为空。
if( is_null($data->name) == FALSE ) {
$class = "show";
}
答案 2 :(得分:0)
SELECT
b.price as price,
b.shop_id as shop_id,
c.image as image,
c.name as name,
a.id as id,
CASE WHEN cart.product_id IS NULL THEN 0 ELSE 1 END as exists_in_cart
FROM products AS a
INNER JOIN prices AS b ON a.ean = b.sku
INNER JOIN shops as c on b.shop_id = c.id
LEFT JOIN cart on a.id = cart.product_id
WHERE a.id = '$product_id'
如果表中不存在该产品,则此查询将返回num_rows = 0,您已选择仅现有产品。