尝试使用表单在表中搜索字符串?

时间:2014-03-31 05:40:41

标签: php mysql

我有一个表单,用户可以在其中输入字符串来搜索数据库

的index.php

<html>
    <head>
        <title>Search the Database</title>
    </head>

    <body>

    <form action="search.php" method="post">
     Search: <input type="text" name="search" /><br />
    <input type="submit" name="submit" value="Submit" />
    </form>

    </body>
</html

从这里我用查询

搜索数据库

的search.php

<?php
mysql_connect ("localhost", "db","pw")  or die (mysql_error());  
mysql_select_db ("stories"); //This selects the specific database you want your results to come from (as you may have more than one database). Change "test" to your database name.

$search = $_POST['search']; //This grabs everything your user has put into the search field (which has been labelled as "search" earlier from the .HTML page).

$sql = mysql_query("select * from stories where stories like '%$term%'");  //Assigns a variable called "$sql" to the result of your "search". And the use of LIKE allows you to only have to type in (for example if you were searching a name).. Jord instead of the full Jordan.

while ($row = mysql_fetch_array($sql)){  //We start a "while" loop so you can output multiple results. Also we assign an array "$row" to each database table column you would like to display. Below is an example if you wanted multiple tables to be searched through and displayed if a match is found.


    echo '<br/> Result '.$row['stories'];

    }

?>

我没有任何错误,但我也没有得到任何输出。查询有问题吗?

1 个答案:

答案 0 :(得分:0)

您将搜索字符串存储在变量$search中,并使用未定义的变量$term进行搜索。试试这个。

$search = $_POST['search']; 
$sql = mysql_query("select * from stories where stories like '%$search%'");