我刚刚看了一个关于如何创建自定义数据库的YouTube视频。我试图实现这到我的网站。然而,很明显,它不工作…
我得到一个错误'查询失败:',并没有从下面的代码更多。
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect to database");
mysql_select_db("$db_name")or die("cannot select DB");
$con=mysqli_connect("$host","$username","$password","$db_name");
$terms = explode(" ", $search);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%each%' ";
else
$query .= "OR keywords LIKE '%each%' ";
}
$query = mysql_query($query);
$numrows = mysql_num_rows($query) or die('Query failed: ' . mysql_error() . "<br />n$sql");
if ($numrows > 0)
while($row = mysqlfetch_ASSOC($query)){
$id = $row['id'];
$title = $row['title'];
$description= $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo '<h2><a href="$link">$title</a><h2>
$description<br/><br/>';
}
else
echo "No results found";
//disconnect
mysql_close();
?>
老实说,我只理解了大约70%,不知道。数据库连接正常且功能正常。我做错了什么?
mysql_num_rows在WHERE "和结束引号之间加空格之前引起了问题,但是在WHERE "和结束引号之间加空格之后,它把我留在了这里。
我不确定这是问题所在,但是,不应该这样:
$query .= "keywords LIKE '%each%' ";
改为
$query .= "keywords LIKE '%{$each}%' ";
它将每个都作为文本处理,而不是作为循环中的字符串。
(下两行相同)
首先是....您需要包含$each来包含变量…不只是每个…
$query .= "WHERE keywords LIKE '%{$each}%' ";
也……将WHERE移到关键字前面,这样如果用户在搜索中没有输入任何内容…他们会质疑一切……否则,如果他们没有输入任何内容,它将中断…
$terms = explode(" ", $search);
$query = "SELECT * FROM search ";
if(!empty($terms)){
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "WHERE keywords LIKE '%{$each}%' ";
else
$query .= "OR keywords LIKE '%{$each}%' ";
}
}