Search code examples
phpmysqlsearch-box

PHP go to 'no results' page


I have a search box and the user should type a transaction number to match a specific record. I was wondering how you would code it if nothing was typed and if it doesn't match a record/doesn't exist. I want it to display No Results, something like that.

search page:

<form action="admin_srchRslt.php" method="get">
  <center>
    <br/>Search Transaction No.<br/>
    <input name="search" type="text" id="search" />
    <input name="btnSearch" type="submit" id="btnSearch" value="Search" />
  </center>
</form>

Solution

  • In admin_srchRslt.php, when you determine that no results were found, use header() to redirect to your "no results" page:

    header("Location: /no_results.html");
    

    A better approach may be to send users to the same page every time but to simply change the results section of the page. If you are using an MVC framework, simply update the 'results' block in your view with the message that no results were found. Otherwise, you could do something like:

    if (empty($results)) // If the $results array contains no data
    {
        echo "No results were found";
    }
    else 
    {
        foreach ($results as $result)
        {
             // Display the result
        }
    }