我正在尝试使用PHP搜索我的网站,但每次搜索某些内容都会显示我没有找到结果!
<form action="search" method="post">
<input type="text" name="search">
<input type="submit" value="Search">
</form>
<?php
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$videosHTML = "";
$searchquery = mysqli_query("SELECT id, Name, Link, Time, Type FROM Videos WHERE Name LIKE '%$searchq%'");
$count = mysqli_num_rows($searchquery);
if ($count == 0){
$videosHTML = "No results found!";
} else{
while($row = mysqli_fetch_array($searchquery)){
$id = $row['id'];
$Name = $row['Name'];
$Link = $row['Link'];
$Time = $row['Time'];
$Type = $row['Type'];
$videosHTML = '<a href="video?id='.$id.'"><div class="thumbnail" style="background-image: ' . "url('thumbnails/" . $id . ".png');" . '"><p class="title">' . $Name . '</p><p class="time">' . $Time . '</p></div></a>' . $videosHTML;
}
}
}
?>
它还向我显示$ searchquery行以及下一行$ count的解析错误。
我认为它没有在$ count中找到任何内容,这就是为什么它可能显示没有找到结果。
答案 0 :(得分:1)
如上所述@Fred -ii-&amp; @RiggsFolly您需要建立有效的数据库连接才能成功查询数据库。假设有一个,并且在这里的代码中它被命名为$dbconn
,那么你还需要在各种mysqli
命令中提供它 - 特别是在这种情况下mysqli_query
方法。
另外,即使您使用的是mysqli,您仍在插入,实际上是用户提供的,直接变量到sql中,因此您需要采取额外的预防措施来防止SQL注入 - 我意识到您过滤掉所有非带有preg_replace的字母数字字符,但那些偷偷摸摸的黑客......!
虽然不在保留字类别中name
和type
是mysql中的关键字,但在数据库查询和列名中应该谨慎对待 - 这是个人偏好我知道但是我在针对db运行查询时,始终将字段封装在反引号中。
<?php
if ( isset( $_POST['search'] ) ) {
/* prepare search term, sanitize as applicable: "belt 'n' braces" */
$searchq = mysqli_real_escape_string( $dbconn, preg_replace( "#[^0-9a-z]#i", "", filter_input( INPUT_POST, 'search', FILTER_SANITIZE_STRING ) ) );
$videosHTML = 'No results found!';
/* supply db connection object in query, unless using Object Orientated approach */
$res = mysqli_query( $dbconn, "SELECT `id`, `Name`, `Link`, `Time`, `Type` FROM `Videos` WHERE `Name` LIKE '%{$searchq}%';");
if( mysqli_num_rows( $res ) > 0 ){
$videosHTML = '';
while( $row = mysqli_fetch_array( $res ) ){
$id = $row['id'];
$Name = $row['Name'];
$Link = $row['Link'];
$Time = $row['Time'];
$Type = $row['Type'];
$videosHTML .= "
<a href='video?id={$id}'>
<div class='thumbnail' style='background-image: url( thumbnails/{$id}.png );'>
<p class='title'>{$Name}</p>
<p class='time'>{$Time}</p>
</div>
</a>\n";
}
}
echo $videosHTML;
}
?>