Php 检查其他表中是否存在id

Php 检查其他表中是否存在id,php,mysql,Php,Mysql,我想检查购物车表中是否存在product\u 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 I

我想检查购物车表中是否存在
product\u 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是
产品id

检查是否返回了任何行,如果有,则设置变量

if($article->num_rows) {
   $class = "show";
} 
或者,检查属性是否不为null

if( is_null($data->name) == FALSE ) {
   $class = "show";
}

为此,我会使用
左连接
(请注意
案例WHEN..THEN..
部分)。它与购物车表联接,并选择一个名为
exists\u in\u cart
的列,如果购物车中存在产品,则该列的值为1,否则为0):

如果购物车中存在产品,则您将获得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'
");
$productInCart = $data->exists_in_cart == 1 ? TRUE : FALSE;
if ($productInCart) {
   $class = 'show';
}
else {
   // ...
}

如果表中不存在产品,此查询将返回num_rows=0,说明您只选择了现有产品。

请详细解释您的问题……仅供参考:我的代码中是否缺少属性而不是函数?我需要签入名为cart的表中的位置是否存在产品,上面的代码只是第一部分,第二个不见了,那一个我不知道怎么做
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'