[英]check if id exist in other table
i want to check if product_id
exist in cart table and if exist define variable $class = 'show'
我想检查product_id
table中是否存在product_id
,如果存在则定义变量$class = 'show'
this is code i have: 这是我的代码:
$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
}
now i dont know how to check if that product exist in cart table. 现在我不知道如何检查该产品是否存在于购物车表中。 in both tables uniqe is product_id
在两个表中,uniqe是product_id
I'd use a LEFT JOIN
for that purpose (notice the CASE WHEN .. THEN ..
section). 为此目的我会使用LEFT JOIN
(请注意CASE WHEN .. THEN ..
部分)。 It joins with cart table and selects a column called exists_in_cart
with a value of 1 if product exists in cart or 0 otherwise): 它与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'
");
You'll then have a 1 if a product exists in a cart or 0 otherwise: 如果产品存在于购物车中,您将获得1或者否则为0:
$productInCart = $data->exists_in_cart == 1 ? TRUE : FALSE;
if ($productInCart) {
$class = 'show';
}
else {
// ...
}
Check any rows were returned, and if there are, set your variable. 检查是否返回了任何行,如果有,请设置您的变量。
if($article->num_rows) {
$class = "show";
}
Or, check that a property is not null. 或者,检查属性是否为空。
if( is_null($data->name) == FALSE ) {
$class = "show";
}
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'
if product doesn't exists in table this query will return num_rows = 0, you have already choosed only existing products. 如果表中不存在该查询,则此查询将返回num_rows = 0,您已经只选择了现有产品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.