【问题标题】:Display error if search cannot be found in SQL?如果在 SQL 中找不到搜索,则显示错误?
【发布时间】:2015-07-10 01:59:28
【问题描述】:

为简单起见,我的搜索框在外部数据库中搜索食物。 搜索工作正常。如果我搜索披萨,代码会在数据库中找到披萨并显示它。如果我搜索鸡肉,代码会找到鸡肉。在数据库等中。

<?php

$searchquery = mysql_real_escape_string(trim($_POST['searchquery'])); //this is how we search and display results 
$find_searchengine=mysql_query("SELECT * FROM searchengine WHERE food_name LIKE '%$searchquery%'"); //we look within the external database 
while($row = mysql_fetch_assoc($find_searchengine))


{
    $food_name = $row['food_name'];

    echo "$food_name<br / >";  //Sorry our servers are down today 

    }

?>

问题是,我的数据库当然不包含世界上所有的食物。所以,如果我搜索让我们说“Rice”,什么都不会出现,页面不会加载任何东西,它不会以任何方式改变,就像按下回车按钮一样。

如果在数据库中找不到某种食物,任何人都可以指导我如何显示错误的正确方向。

【问题讨论】:

  • 除了下面的答案,您可能还想查看转换为 PDO 和准备好的语句,您当前的代码已被弃用,并将在未来的 PHP 版本中删除

标签: php html sql error-handling


【解决方案1】:

只需添加一个检查查询是否获得任何记录。试试 -

if(mysql_num_rows($find_searchengine) > 0) {
     // process data
} else {
     //display error
}

【讨论】:

    【解决方案2】:
       if(empty($row['food_name']))
        print"Food is not found":
    

    【讨论】:

    • 非常感谢,它运行良好。您是否知道如何在“找不到食物”句子之前出现搜索词。所以...可以说(大米“未找到”)
    • 通过url发送输入的单词。喜欢 header("location: page.php?word=".$enteredword)
    【解决方案3】:

    试试这样:

    if(mysql_num_rows($find_searchengine) > 0){
    while($row = mysql_fetch_assoc($find_searchengine))
    {
        $food_name = $row['food_name'];
    
        echo "$food_name<br / >";  //Sorry our servers are down today 
    
        }
    }else{
          echo "not match found for search criteria";
    }
    

    注意:首先停止使用 mysql 并启动 mysqli 或 pdo。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多