Displaying message when no results found in PHP MySQL search

前端 未结 8 1910
独厮守ぢ
独厮守ぢ 2020-12-11 07:07

I have a PHP search script which queries a MySQL database. Currently, when no results are displayed the script shows and error. How can I make it display a message like \"No

相关标签:
8条回答
  • 2020-12-11 07:35

    Try the following:

    <?php
    
    mysql_connect("localhost","username","password");
    mysql_select_db("database");
    
    if(!empty($_GET['q'])){
    $query=mysql_real_escape_string(trim($_GET['q']));
    $searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%'  LIMIT 8";
    $searchResult=mysql_query($searchSQL);
    
    if(mysql_num_rows($searchResult) <= 0)
    {
        echo "No results";
    } else {
    
        while ($row=mysql_fetch_assoc($searchResult)){
            $results[]="<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
        }
    
        echo implode($results);
    } 
    }
    
    ?>
    

    Also please either use MySQLi or PDO as it is safer and better to use, some information can be found below. Personally I prefer MySQLi but prepared statements in PDO is really good and saves some lines of code every time you query ;)

    MySQLi and PHP

    PDO and PHP

    0 讨论(0)
  • 2020-12-11 07:42
    if (empty($results)) { 
        echo 'No results found'; 
    } else {
        echo implode($results);
    }
    
    0 讨论(0)
提交回复
热议问题