Jump to content

Blank Search Displays All Records, Help!!!


pauldonnelly23

Recommended Posts

Hey Everyone,

 

Please can someone help, When I use my search script, leave my form blank and click search all my records appear.

I REALLY do not want this, can someone look at my code and see what code I need to stop this.

 

Many Thanks

 

Paul

 

<form method="post" action="search.php">
<input type="text" name="search" size=25 maxlength=25>
<input type="Submit" name="Submit" value="Search Now">
</form>

<?php

include "config.php";

$search=$_POST["search"];
              
$result = mysql_query("SELECT * FROM pubdirectory " .
"WHERE pubname LIKE '%".$search."%'".
" OR pubcounty LIKE '%".$search."%'" .
" ORDER BY pubcounty");  


                                  
if (mysql_num_rows($result) == 0) {
echo "Whoops!! <br> No results were found searching for <strong>$search</strong>. <br> Please try again.";

exit;
}


          
while($r=mysql_fetch_array($result))
{      
   $pubname=$r["pubname"];
   $pubaddress=$r["pubaddress"];
   $pubtown=$r["pubtown"];
   $pubcounty=$r["pubcounty"];
   $pubdetails=$r["pubdetails"];
   $pubweb=$r["pubweb"]; 
   $pubdir_id=$r["pubdir_id"];
   
                   
   echo "$pubname <br> $pubtown <br> $pubcounty <br> $pubdetails <br> $pubweb <br><hr>";
}
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}  
?>

Link to comment
Share on other sites

All you need to do is check to see if the string has some characters.  If you want you can handle it the say way you do when there are no rows.

 

<?php

include "config.php";

$search=$_POST["search"];

// If the search string doesn't contain at least one of a-z, A-Z, _, or 0-9 it is invalid
if (!preg_match('/\w/', $search)) {
echo "Whoops!! <br> Invalid search string. <br> Please try again.";

exit;
}

              
$result = mysql_query("SELECT * FROM pubdirectory " .
"WHERE pubname LIKE '%".$search."%'".
" OR pubcounty LIKE '%".$search."%'" .
" ORDER BY pubcounty");  
if (mysql_num_rows($result) == 0) {
echo "Whoops!! <br> No results were found searching for <strong>$search</strong>. <br> Please try again.";

exit;
}


Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.