我正在构建一个返回数据的搜索引擎,如果数据库中没有结果,我将无法显示消息。我是MYSQLI的初学者。我该怎么办呢?我累了计算行数,如果它们小于0则显示它但是我在编写时遇到了错误。
代码:
<?php
$db = mysqli_connect('localhost','root', '', 'searchengine');
if(!$db) {
die('sorry we are having some problbems');
}
$searchTerm = mysqli_real_escape_string($db,$_GET['term']);
$searchTerm = trim($searchTerm);
if ($searchTerm == '') {
echo("no key words searched please try again");
}
else
{
$sql = mysqli_query(
$db,
sprintf(
"SELECT * FROM searchengine WHERE name LIKE '%s' LIMIT 0,20",
'%'. $searchTerm .'%'
)
);
while($ser = mysqli_fetch_array($sql)) {
echo "<a href='$ser[pageurl]'>$ser[img]</a>";
}
}
mysqli_close($db);
?>
答案 0 :(得分:1)
使用mysqli_num_rows
...
$sql = mysqli_query(
$db,
sprintf(
"SELECT * FROM searchengine WHERE name LIKE '%s' LIMIT 0,20",
'%'. $searchTerm .'%'
)
);
if(mysqli_num_rows($sql) === 0) {
echo "No results.";
}
答案 1 :(得分:-1)
因为mysqli_fetch_array()
在没有结果时返回null,所以你也可以放
if ($ser === NULL){
echo "no results";
}
最后