使用PHP / MYSQL搜索功能

时间:2013-11-20 13:35:30

标签: php mysql

我正在尝试创建搜索功能。在得到一些错误后我一直在研究和编辑,现在我没有得到任何错误,但没有任何回应。我完全难过,我想知道是否有人知道它有什么问题。提前谢谢! :D

<html>
<head>
<title>Search Query</title>
</head>

<body>
<?php
$con = mysql_connect ("localhost", "root", "");
mysql_select_db ("music", $con);

if (!$con)
{ 
die ("Could not connect: " . mysql_error());
} 
$sql = mysql_query("SELECT * FROM entries WHERE Title LIKE '%term%'") or die (mysql_error());

while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)){
echo 'Title: ' .$row['Title'];
echo '<br /> Artist: ' .$row['Artist'];
echo '<br /> Album: '.$row['Album'];
echo '<br /> Location: '.$row['Location'];
echo '<br /> Media: '.$row['Media']; 
}

mysql_close($con);
?>
</body>
</html>

这是我使用的表格:

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

4 个答案:

答案 0 :(得分:2)

您必须将变量传递给此查询:

$term = mysql_real_escape_string($_GET['term']);
mysql_query("SELECT * FROM entries WHERE Title LIKE '%" . $term . "%'");

答案 1 :(得分:0)

你的PHP代码不正确,你使用'term'作为字符串而不是PHP值,你需要把它变成$ _GET [“name”]所以它看起来像这样

$sql = mysql_query("SELECT * FROM entries WHERE Title LIKE '%". $_GET["term"] ."%'") or die (mysql_error());

!!! HOWEVER !!! 这是非常不安全的,因为它会允许某人SQL注入您的应用程序。所以不要像这样使用它。过滤提供的'term'值并仅留下A-Za-z0-9(或类似),使用正则表达式删除其余部分。

答案 2 :(得分:0)

的index.php

<!DOCTYPE html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form action="search.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

的search.php

<html>
<head>
<title>Search Query</title>
</head>

<body>
<?php

if($_POST['term']){

    $term = mysql_real_escape_string($_POST['term']);

$con = mysql_connect ("localhost", "root", "");
mysql_select_db ("music", $con);

if (!$con)
{ 
die ("Could not connect: " . mysql_error());
} 
$sql = mysql_query("SELECT * FROM entries WHERE Title LIKE '%" . $term . "%'") or die (mysql_error());

while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)){
echo 'Title: ' .$row['Title'];
echo '<br /> Artist: ' .$row['Artist'];
echo '<br /> Album: '.$row['Album'];
echo '<br /> Location: '.$row['Location'];
echo '<br /> Media: '.$row['Media']; 
}

mysql_close($con);
}else{
    echo 'No search term found';
}
?>
</body>
</html>

将两个页面放在同一个文件夹中。

答案 3 :(得分:0)

$term = mysql_real_escape_string($_POST['term']);

if ($stmt = $mysqli->prepare("select *
                               . "  from entries"
                               . " where Title like ?")) 
    {
       $stmt->bind_param("i", "%$term%");
       $stmt->execute();
       //then fetch value
    } else {
      /* handle SQL error */
    }