PHP搜索和查询结果

时间:2013-09-17 13:32:51

标签: php search

这是我的问题。我有一个我想要按名称搜索的数据库。如果有相似的名字,我希望它弹出并提供选择哪一个。一旦你这样做并点击搜索就会进入search.php文件...我想显示结果,但GET方法似乎不起作用。 这是我的表格。

<form action="search.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Search" />

这是我的PHP搜索

<?php
mysql_connect("localhost", "dbname", "password") or die("Error connecting to database: ".mysql_error());
/*
    localhost - it's location of the mysql server, usually localhost
    root - your username
    third is your password

    if connection fails it will stop loading the page and display an error
*/

mysql_select_db("ambassador") or die(mysql_error());
/* tutorial_search is the name of database we've created */


$query = $_GET['query'];
// gets value sent over search form

$min_length = 3;
// you can set minimum length of the query if you want

if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

    $query = htmlspecialchars($query);
    // changes characters used in html to their equivalents, for example: < to &gt;

    $query = mysql_real_escape_string($query);
    // makes sure nobody uses SQL injection

    $raw_results = mysql_query("SELECT * FROM member
        WHERE (`Name` LIKE '%".$query."%')") or die(mysql_error());

    if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

        while($results = mysql_fetch_array($raw_results)){

        }

    }
    else{ // if there is no matching rows do following
        echo "No results";
    }

}
else{ // if query length is less than minimum
    echo "Minimum length is ".$min_length;
}
?>

然后我尝试使用此方法从数据库中获取结果。

<?php echo $_GET['Name']; ?>

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这不是答案,我把代码放在这里因为它在评论中没有很好地形成。 因此,尝试这部分代码,它应该根据表单中的名称显示结果:

HTML:

<form action="search.php" method="GET">
<input type="text" name="name" />
<input type="submit" value="Search" />
</form>   

PHP:

 <?php
    mysql_connect("localhost", "dbname", "password") or die("Error connecting to database: ".mysql_error());
    mysql_select_db("ambassador") or die(mysql_error());

    //check if variable $_POST['name'] has a value
    if(isset($_GET['name'])) $name=$_GET['name'];
    else $name="";

    $raw_results = mysql_query("SELECT * FROM member where name='".$name."'") or die(mysql_error());


            while($results = mysql_fetch_array($raw_results,MYSQL_ASSOC)){

                echo $results['name'].'<br/>';
            }
     ?>