我花了几个小时试图做到这一点。搜索中没有解决方案帮助我,所以我终于问了。
我要做的是:如果未找到结果,则显示一条消息。
这就是我所拥有的,目前它并没有让我沮丧。
$sql = mysql_query("SELECT * FROM cover WHERE MATCH(keyword,description,categories) AGAINST('$search_key' in boolean mode) ORDER BY id DESC LIMIT $from , $perPage");
$i=1;
while($result = mysql_fetch_object($sql)) {
$keyword = $result->keyword;
$img = $result->img;
$description = $result->description;
if($img != null) { DO THIS;
if($i==2) { require_once(dirname(__FILE__).'/page.php'); }
$i++; }
}
if($img == null) { print "<center>No Results Found</center>"; }
我不知道如何使用mysql_num_rows(这是我看到的网站上最受欢迎的解决方案),它返回一个错误,我认为它不适用于mysql_fetch_object($sql)
? 我不认为这一点:$img = $result->img;
也会与mysql_num_rows合作。
我只是想找到一种方法来做到这一点,而不必修改括号内的任何内容,只需修改括号外的任何内容。
当我说"不起作用"时,我的意思是它不会显示如果未找到结果应该显示的消息。我已经测试了if($img != null) { print "<center>No Results Found</center>"; }
,它工作正常,它显示了消息。但它似乎不能以另一种方式工作,我现在只是感到困惑。
如果您对mysql_num_rows有疑问,请查看您的索引:
$i = 1;
如果没有结果,则循环后的值仍将为 1,因此您需要检查 AFTER while 循环:
if($i == 1) { print "<center>No Results Found</center>"; }
以下方法有效:
$sql = mysql_query("SELECT * FROM cover WHERE MATCH(keyword,description,categories) AGAINST('$search_key' in boolean mode) ORDER BY id DESC LIMIT $from , $perPage");
if(mysql_num_rows($sql) > 0)
{
$i=1;
while($result = mysql_fetch_object($sql))
{
$keyword = $result->keyword;
$img = $result->img;
$description = $result->description;
if($img != null)
{
DO THIS;
if($i==2)
{
require_once(dirname(__FILE__).'/page.php');
}
$i++;
}
}
}
else
{
print "<center>No Results Found</center>";
}
我认为当您可以直接使用该$result->keyword
时,您没有理由要将$result
中的值存储到单独的变量中。
您的问题是 while() 循环仅在返回结果时才会发生,因此永远不会在此内部引发 NULL 比较。
我建议你需要像这样对代码重新排序:
$sql = mysql_query("SELECT * FROM cover WHERE MATCH(keyword,description,categories) AGAINST('$search_key' in boolean mode) ORDER BY id DESC LIMIT $from , $perPage");
$numResults = mysql_num_rows($sql);
if ($numResults === 0) { // mysql_query returned no results
print "<center>No Results Found</center>";
} else {
require_once(dirname(__FILE__).'/page.php');
while($result = mysql_fetch_object($sql))
{
$keyword = $result->keyword;
$img = $result->img;
$description = $result->description;
}
}
你可以这样使用它
if(mysql_num_rows($result) <= 0);
{
echo 'There is no result';
}
else
{
your code
}
这是在您的代码中实现的
$sql = mysql_query("SELECT * FROM cover WHERE MATCH(keyword,description,categories) AGAINST('$search_key' in boolean mode) ORDER BY id DESC LIMIT $from , $perPage");
$i=1;
$result = mysql_fetch_object($sql);
if(mysql_num_rows($result) > 0 )
{
while($result) {
$keyword = $result->keyword;
$img = $result->img;
$description = $result->description;
if($img != null) { DO THIS;
if($i==2) { require_once(dirname(__FILE__).'/page.php'); }
$i++; }
}
if($img == null) { print "<center>No Results Found</center>"; }
}
else
{
echo 'There is no result';
}