php搜索栏当我按下提交时,搜索栏中没有任何内容显示所有数据

时间:2014-10-08 19:44:18

标签: php database search echo

搜索融合工作正常,但如果我在搜索栏中没有任何内容提交,则会显示所有数据。我如何收到一条消息,表示没有任何内容输入搜索栏?。我是PHP的新手。

<?php
        $mysql_host="host";
        $mysql_database="database";
        $mysql_user="username";
        $mysql_password="password";

        $dbconnect=@mysql_connect($mysql_host, $mysql_user, $mysql_password);
        // trys to connect to the database


        if (!$dbconnect) {
            exit("An error has occurred - could not connect to the database.");
            // if couldn't connect, let the user know
        }

        if(!mysql_select_db($mysql_database)) {
            exit("An error has occurred - Could not select the database.");
            //if couldn't select db, let the user know
        }


    $output = '';
    //collect

    if(isset($_POST['search'])) {
        $searchq = $_POST['search'];
        $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
        $query = mysql_query("SELECT * FROM people WHERE firstname LIKE '%" . $searchq . "%' OR surname LIKE '" . $searchq . "';");
        $count = mysql_num_rows($query);
        if($count == 0) {
            $output = 'There was no search results!';
        } else {
            while ($row = mysql_fetch_array($query)) {
                $fname = $row ['firstname'];
                $lname = $row ['surname'];
                $id = $row ['id'];

                $output .= '<div>'.$fname.' '.$lname.'</div>';


            }

        }

    }
    ?>
    <html>
    <head>
    <title>search</title>
    </head>
    <body>

        <form action="index.php" method="post">
            <input type="text" name="search" placeholder="Search here......." />
            <input type="submit" value="submit" />


        </form>



        <?php print("$output");?>





    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

如果您想避免在提交表单时显示的所有结果,您需要检查文本输入中提交的内容。

现在,如果$searchq == ""那么你的SQL查询会搜索:WHERE firstname LIKE '%%'这只是一个通配符。

要解决此问题,请将$_POST['search'] != ""添加到初始条件。

<?php

// Make sure to only perform the search and show the results if there's something to search for
if(isset($_POST['search']) && $_POST['search'] != "") {
    $searchq = $_POST['search'];
    $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
    $query = mysql_query("SELECT * FROM people WHERE firstname LIKE '%" . $searchq . "%' OR surname LIKE '" . $searchq . "';");
    $count = mysql_num_rows($query);

    if($count == 0) {
        $output = 'There was no search results!';
    } else {
        while ($row = mysql_fetch_array($query)) {
            $fname = $row ['firstname'];
            $lname = $row ['surname'];
            $id = $row ['id'];

            $output .= '<div>'.$fname.' '.$lname.'</div>';
        }
    }
}

现在它只会搜索表单提交时带有要搜索的字符串!