如果搜索框中没有输入任何内容,则使用jQuery即时搜索会提供所有字段

时间:2015-02-17 09:35:50

标签: php jquery

这是我的主要搜索部分的PHP代码 此搜索工作正常,但在一种情况下:如果在搜索框中没有输入任何内容,它将返回表中的所有值 我该如何解决这个问题?

<?php
    mysql_connect("localhost","root","0392") or die("Could not connect");
    mysql_select_db("emm") or die("could not connect");
    $output="";
    if(isset($_POST['searchVal'])){
      $searchq = $_POST['searchVal'];
      $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

      $query=mysql_query("select name, code from employee_table where name LIKE     '%$searchq%' or code LIKE '%$searchq%'");
      $count = mysql_num_rows($query);

      if($count == 0){
        $output='No Matching Results Found !!';
      }
      else{
        while($row = mysql_fetch_array($query)){            
          $name = $row['name'];
          $code= $row['code'];

          $output.="<a href='altprofile.php?cod=".$code."'><div class='col-md-3'><input type='text' name='nam' disabled='disabled' value='".$name."'></input></div></a> ";
        }
      }
    }
    echo($output);
?>

3 个答案:

答案 0 :(得分:0)

试试这个

 ...
 if(isset($_POST['searchVal']) && $_POST['searchVal'] != ''){
   $searchq = $_POST['searchVal'];
   $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

   $query=mysql_query("select name, code from employee_table where name LIKE     '%$searchq%' or code LIKE '%$searchq%'");
   $count = mysql_num_rows($query);

   if($count == 0){
     $output='No Matching Results Found !!';
   }
   else{
     while($row = mysql_fetch_array($query)){
       $name = $row['name'];
       $code= $row['code'];

       $output.="<a href='altprofile.php?cod=".$code."'><div class='col-md-`enter code here`3'>`enter code here`<input type='text' name='nam' `enter code here`disabled='disabled' value='".$name."'></input></div></a> ";
     }
  }
}
...

注意:不要使用mysql使用mysqli或PDO

答案 1 :(得分:0)

只需使用

if(isset($_POST['searchVal']) && !empty($_POST['searchVal'])){

// DO code

}else{
  echo "no results";
}

答案 2 :(得分:0)

只需执行以下两项操作,如果条件为

则更改
//checks value is not empty
if(isset($_POST['searchVal']) && !empty($_POST['searchVal']))
{
  //all your stuff
}
else
{
echo "No results"
}