Displaying message when no results found in PHP MySQL search

前端 未结 8 1909
独厮守ぢ
独厮守ぢ 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:18
    <?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);
    
        // the query was run successfully 
        // and it returned at least a result
        if(is_resource($searchResult) && mysql_num_rows($result) > 0){
            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);
        } else{
            echo 'No Results were found';
        }
    }
    ?>
    
    0 讨论(0)
  • 2020-12-11 07:23

    You could count the number of elements in the array, and either continue with your implode or display the message you mentioned.

    <?php
         if(count($results) > 0){
             echo implode($results);
         }
         else {
             echo "No results were found.";
         }
    ?>
    

    You also really should not be using the mysql_* functions. Use either the improved version (mysqli_*) or PDO.

    0 讨论(0)
  • 2020-12-11 07:23
    if (mysql_num_rows($searchResult) == 0) {
       echo "some error message"; 
    } else { 
      ... process data
    }
    
    0 讨论(0)
  • 2020-12-11 07:33

    You could also use the function mysql_num_rows, which will tell you the number of rows returned by your query.

    $rows = mysql_num_rows($searchResult);
    if($rows <= 0){
        /* Code if there are no rows */
    }
    else{
        /* At least one row has been found */
    }
    
    0 讨论(0)
  • 2020-12-11 07:33

    How about a simple counter in the while statement:

    $i = 0;
    
    while (condition) {
       $i++;
       do stuff;
    }
    
    if ($i ==0) {echo 'No results found';}
    
    0 讨论(0)
  • 2020-12-11 07:34

    Create a MYSQL Connection and paste this code below

    $sql="SELECT * FROM tablename WHERE columnname LIKE your variable or constant ";
    $result=mysql_query($sql);
    
    $count=mysql_num_rows($result);
    
    if($count>=1){if result was found}
    
    else {if result was not found}
    
    ?>
    
    0 讨论(0)
提交回复
热议问题