在PDO准备语句中使用if else连接查询

时间:2015-01-24 10:47:12

标签: php mysql pdo mysqli prepared-statement

我试图将简单的MySQLi查询转换为PDO预处理语句 这是旧代码

if($mode=='')
{
    $query="SELECT * FROM items WHERE 1";
    if($CuisineId != '')
    {
        $query=$query. " AND CuisineId='$CuisineId' ";
    }
    if($CategoryId != '')
    {
        $query=$query. " AND CategoryId='$CategoryId'  ";
    }
    if($DietId != '')
    {
        $query=$query. " AND DietId='$DietId' ";
    }

    $query=$query. " ORDER BY Name ";

    $result= execute_query($con,$query) or die(mysqli_error($con));
    echo "<option value=''>Select One</option>";
    while ($row=mysqli_fetch_array($result)) {
        echo "<option value=". $row['Id'] .">" . $row['Name'] . "</option>";
    }
}

带有预处理语句的新代码看起来像这样,并且工作正常

if($mode=='')
{
    $query="SELECT * FROM items WHERE 1";
    if($CuisineId != '')
    {
        $query=$query. " AND CuisineId=? ";
    }
    if($CategoryId != '')
    {
        $query=$query. " AND CategoryId=?  ";
    }
    if($DietId != '')
    {
        $query=$query. " AND DietId=? ";
    }

    $query=$query. " ORDER BY Name ";
    $stmt = $con->prepare($query);
    $stmt->execute(array($CuisineId,$CategoryId,$DietId));
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    echo "<option value=''>Select One</option>";
    while($row = $stmt->fetch()) {
        echo "<option value=". $row['Id'] .">" . $row['Name'] . "</option>";
    }
}

这个新代码工作正常,但这是新代码中最糟糕的情况。 如果$CuisineId$CategoryId$DietId为空,该怎么办?查询将不会连接并在此行上引发错误

$stmt->execute(array($CuisineId,$CategoryId,$DietId));

如果我开始做IF ELSE会有所有可能性,它会使我的代码太长。有没有办法解决这个问题?

提前谢谢你:)

1 个答案:

答案 0 :(得分:0)

您不需要与此查询连接

SELECT * 
FROM items 
WHERE (? is null or CuisineId = ?)
  and (? is null or CategoryId = ?)
  and (? is null or DietId = ?)
ORDER BY Name