搜索输入验证(空输入显示“无搜索结果”)

时间:2013-12-02 07:18:55

标签: php mysql search

我正在使用php进行搜索程序。下面是我的代码。它的运行,但当我点击搜索按钮时,它仍然打印输出。我想要的是,如果我点击按钮搜索而不在其文本上输入内容,它将打印消息“$ output ='没有搜索结果'”。我该怎么做?提前谢谢......

<input type="text" name="search" placeholder="Search...">
<input type= 'submit' name= 'btnsearch' value= 'search' id= 'btnsearch' onclick=         'this.form.action'/>
<input type = 'submit' name = 'download' value = 'save to excel'/>


<?php
mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("copylandia") or die ("could not find db");


$output = '';
if(isset($_POST['btnsearch']))
{
$searchq = $_POST['search'];
/*$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);*/

$query = mysql_query("SELECT * FROM user WHERE initial LIKE '%$searchq%' OR lname             LIKE '%$searchq%'") or die ("could not search");
$count = mysql_num_rows($query);

if($count == FALSE)

{

$output = 'There was no search results!';

}
else
{ 
while($row = mysql_fetch_array($query)){
$id = $row['number'];
$Initials = $row['initial'];
$name = $row['fname'];
$lastname = $row['lname'];
$middle = $row['mname'];
$email = $row['emailadd'];
$uname = $row['username'];
$pass = $row['password'];
$Group = $row['group'];
$Position = $row['position'];
$Level1 = $row['level1'];
$Level2 = $row['level2'];
$Level3 = $row['level3'];
$Level4 = $row['level4'];
$Level5 = $row['level5'];
$Level6 = $row['level6'];
$Level7 = $row['level7'];

$output .= 'Initial : '.$Initials.'<br> 
First Name : '.$name.'<br> 
Last Name : '.$lastname.' <br> 
Middle Name : '.$middle.' <br> 
Email Add : '.$email.'<br> 
Username : '.$uname.'<br> 
Password : '.$pass.'<br> 
Group : '.$Group.'<br> 
Position : '.$Position.'<br> 
Level 1 : '.$Level1.'<br> 
Level 2 : '.$Level2.'<br> 
Level 3 : '.$Level3.'<br> 
Level 4 : '.$Level4.'<br> 
Level 5 : '.$Level5.'<br> 
Level 6 : '.$Level6.'<br> 
Level 7 : '.$Level7.'<br>
-------------------------------------<br>';

}

}

print "$output";
}
?>

<?php 

3 个答案:

答案 0 :(得分:1)

更改此

    if(isset($_POST['btnsearch']))
    {
    $searchq = $_POST['search'];

    to this




    if(isset($_POST['btnsearch']))
        {
        $searchq =trim(strip_tags( $_POST['search']));  
$query = mysql_query("SELECT * FROM user WHERE initial LIKE '%$searchq%' OR lname    LIKE '%$searchq%'") or die ("could not search");
$count = mysql_num_rows($query);

    // you can also use empty($searchq)
        if(!strlen($searchq) >0 || $count==FALSE)
        {
        print whatever you want to print here
        }

请停止使用 mysql_query

在弃用之前已弃用。

答案 1 :(得分:1)

检查搜索关键字,而不是查询如下

$searchq = trim($_POST['search']);
if(!empty($searchq)){
    // query 
}else {
    $output = 'There was no search results!';

}

答案 2 :(得分:0)

您可以使用不允许您在搜索框中输入内容的js函数。

并且你也可以在php代码中处理这个问题,你提交的文本框值是空的。