0

我有一个简单的 php mysql 搜索来搜索数据库,但是,我似乎无法让它从搜索字段和类别中搜索文本,但我只希望它在选择时搜索类别,

这是我尝试过的代码:

if ($search !== null){

    $sql = "SELECT * FROM people WHERE MATCH (lname,fname) AGAINST (:search IN BOOLEAN MODE) ORDER BY price ".$price." LIMIT ".$start.", ".$limit;

    $q   = $conn->prepare($sql) or die("failed!");
    // Bind the params to the placeholders
    $q->bindParam(':search', $search, PDO::PARAM_STR);
    $q->execute();
}


if ($search !== null && $category !== null){

    $sql = "SELECT * FROM people WHERE MATCH (lname,fname) AGAINST (:search IN BOOLEAN MODE) and category=:category ORDER BY price ".$price." LIMIT ".$start.", ".$limit;

    $q   = $conn->prepare($sql) or die("failed!");
    // Bind the params to the placeholders
    $q->bindParam(':search', $search, PDO::PARAM_STR);
    $q->bindParam(':category', $category, PDO::PARAM_STR);
    $q->execute();
}

但是,如果选中,这仍然会忽略类别字段选项!有任何想法吗?

它们的设置如下:

   // Check and set category
$category = (!empty($_GET['category']) ? $_GET['category'] : null);

// Check and set search
if(!empty($_GET['search'])){
    $search = $_GET['search'];
}else{
    $search = null;
}
4

1 回答 1

1

做一些调试以确保$search$category正在设置。这很可能是你的问题。从它的外观来看,$category应该设置(因为你说它来自查询字符串),但只需检查两者以确定。就像是:

if($category !== null)
    die("category = $category");
else {
    die("no category");
}
//do same test for $search

如果用户从链接 ( <a href="search.php?category=Books">Books?</a>) 访问此页面,我看不出如何$_GET['search']设置。

我建议您更改您的if语句以提高效率(只有 1 应该执行):

if ($search !== null){
    if($category !== null){
        //query with category
    }
    else {
        //query w/o category
    }
}

另外,我会isset()用来检查这些变量是否被实例化而不是empty().

于 2012-10-11T18:10:50.220 回答