简体   繁体   English

MySQL:查询多个条件

[英]MySQL:Query with multiple conditions

Im creating detailed product search.I verified that ,my variables are posted correctly, but the query don't finding anything. 我正在创建详细的产品搜索。我验证了,我的变量已正确发布,但查询未找到任何内容。 My question is: 我的问题是:

What could be wrong in this query and what could be the best solution for detailed search in SQL? 此查询可能有什么问题,什么是SQL中详细搜索的最佳解决方案?

<?php

if ( 
    isset($_POST["productName"]) || isset($_POST["searchCategory"]) || 
    isset($_POST["searchManufacturer"]) || isset($_POST["costFrom"]) || 
    isset($_POST["costTo"])
){

    $stmt=$user_home->runQuery("SELECT* FROM Products
        WHERE (productTitle='$_POST[productName]' OR '$_POST[productName]' IS NULL)
        AND   (category='$_POST[searchCategory]' OR '$_POST[searchCategory]' IS NULL)
        AND   (manufacturer='$_POST[searchManufacturer]' OR '$_POST[searchManufacturer]' IS NULL)

    ");
    echo $stmt->rowCount();
} 

Try to proper forming WHERE statement. 尝试正确形成WHERE语句。 You should add conditions for productTitle , category , manufacturer fields only then isset proper POST fields. 您应该添加条件productTitlecategorymanufacturer领域才isset适当POST领域。

Try this code: 试试这个代码:

<?php

if (
    isset($_POST["productName"]) || isset($_POST["searchCategory"]) ||
    isset($_POST["searchManufacturer"]) || isset($_POST["costFrom"]) ||
    isset($_POST["costTo"])
){
    $conditions = array();
    if (isset($_POST['productName'])) {
        $conditions[] = "(productTitle='".$_POST['productName']."')";
    }

    if (isset($_POST['category'])) {
        $conditions[] = "(category='".$_POST['searchCategory']."')";
    }

    if (isset($_POST['searchManufacturer'])) {
        $conditions[] = "(manufacturer='".$_POST['searchManufacturer']."')";
    }
    $where = implode(' AND ', $conditions);
    if ($where) {
        $where = 'WHERE '.$where;
    } else {
        $where = "";
    }

    $stmt=$user_home->runQuery("SELECT * FROM Products ". $where);
    echo $stmt->rowCount();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM