我不知道如何在sql中使用$where来处理选定的类别

8aqjt8rx  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(341)

我想显示从表中选择的查询

<?php 
    $where = "";

    if(isset($_GET['category']))
    {
        $catid = $_GET['category'];
        $where = " WHERE product.categoryid = $catid";
    }

这就是问题所在 $where 函数获取类别

$sql = "SELECT category.*,  
             category.category_id , items.id AS itemID,items.asset_tag,items.name,
                  items.brand,items.status,
                  items.quantity,items.category_id,
                items.color,items.texture,items.photo,items.date,
             items.fetch_item FROM items  LEFT JOIN category ON 
                     category.category_id=items.category_id 
                  WHERE  items.status = 'Available' AND items.fetch_item = '0' $where";

         ?>
ac1kyiln

ac1kyiln1#

看起来您犯了一个小错误,因为在“默认”查询中您已经 WHERE 语句,所以在 AND 或者 OR 而不是 WHERE 再一次:

$where = "";
if(isset($_GET['category']))
{
    $catid=$_GET['category'];
    $where = " AND product.categoryid = $catid";
}

另外,你可以注射额外的 WHERE 通过使用sprintf()函数,条件变得更加优雅。请看下面的示例:

$additional_condition = 'AND active=1'
$statement = 'SELECT * FROM users WHERE condition=1 %s';
echo sprintf($statement, $additional_condition);

// Output: SELECT * FROM users WHERE condition=1 AND active=1

相关问题