【发布时间】:2013-01-18 01:56:02
【问题描述】:
在我正在制作的网站中,我需要一个搜索引擎来查找歌曲供人们收听。我让它可以从数据库中获取信息并将它们显示在页面上。当有两首同名歌曲时,问题就来了。我有一个系统,因此结果将转到单独的链接,但是当我搜索它们时,即使它们有两个单独的来源,它们也会显示相同的图像。由于某种原因,它也会产生额外的结果。这是我的代码:
<?php
if (isset($_GET['q'])) {
$q = $_GET['q'];
mysql_connect('********', '********', '********');
mysql_select_db('********');
$query = mysql_query("SELECT * FROM ******** WHERE title LIKE '$q'");
$numrows = mysql_num_rows($query);
} else {
echo "
<span style='font-family: Helvetica, Arial;font-weight: bold;font-size: 25px;'>Search</span>
<form action='http://www.example.com/search' method='get'>
<input placeholder='Search for music' type='text' name='q' style='font-weight:bold;padding:5px;width:300px;border-top-left-radius: 4px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 4px;border: 3px solid gray;background-color:#000000;color:#FFFFFF;' />
</form>
";
}
if ($numrows != 0) {
$index = 0;
$results = array();
while($row = mysql_fetch_assoc($query)) {
$results[$index] = $row;
$index++;
foreach ($results as $result) {
$url = "http://www.example.com?id=" . $row['id'];
$title = $row['title'];
$arturl = $row['art_url'];
if ($_GET['q'] != "") {
echo "
<a href='$url'>
<table>
<tr style='text-align:left;'>
<td><img src='$arturl' style='width:100px;height:100px;'></td>
<td>
<span class='songTitle'>$title</span>
<br/>
<span class='songArtist'>By: Unknown</span>
</td>
</tr>
</table>
</a>
<br />
";
}
}
}
} else {
if ($_GET['q'] != "") {
echo "
<span style='font-family: Helvetica, Arial;font-weight: bold;font-size: 25px;'>Search</span>
<form action='********' method='get'>
<input placeholder='Search for music' type='text' name='q' style='font-weight:bold;padding:5px;width:300px;border-top-left-radius: 4px;border-top-right-radius: 10px;border-bottom-left-radius: 10px;border-bottom-right-radius: 4px;border: 3px solid gray;background-color:#000000;color:#FFFFFF;' />
</form>
";
echo "<br />No results where found.";
}
}
?>
【问题讨论】:
-
如果你使用
mysql_函数,你肯定不会有一个很好的搜索引擎。它们不再维护and are officially deprecated。看到red box?改为了解prepared statements,并使用PDO 或MySQLi - this article 将帮助您决定哪个。 -
好的,我会读的。但是现在我需要在完全改变网站之前让它工作!
-
我认为您不了解使用您拥有的代码的后果。
-
^^^^虽然如此,但对于普通 S.O 用户来说,每天看 10 次就有点乏味了。
-
@Gordan: "在我彻底改变网站之前" - 将字母
i插入到每个mysql_函数调用中(这几乎就是 切换到 MySQLi 的必要)并不是什么大不了的事。当然,也应该借此机会对语句进行参数化 - 但这是另一回事。