简体   繁体   English

如果查询未返回任何结果,如何停止执行脚本

[英]How to stop execution of the script if query does not return any result

In my page I have multiple company_id . 在我的页面中,我有多个company_id Some of those did not return any result in the following query. 其中一些在以下查询中未返回任何结果。

My question is what should I do for them? 我的问题是我应该为他们做什么? Should I leave the code as is or should I stop the execution if there is nothing found? 如果什么都没找到,我应该保留代码还是应该停止执行? If yes, how can I do this? 如果是,我该怎么做?

<?php
   $categories = mysql_query('SELECT distinct(category),id FROM products WHERE company_id = ' . $cid );
   while($cat = mysql_fetch_assoc($categories)) 
   {
      echo "<a href='#'>" . $cat['category'] . "</a><br>";
   }
?>

to stop executing in a while loop use break statement 停止在while循环中执行,使用break语句

something like 就像是

while($cat = mysql_fetch_assoc($categories)) 
{
   if ( $cat['category'] == '' )
      break;                   
   echo "<a href='#'>" . $cat['category'] . "</a><br>";
}

keep in mind that this will stop the loop immediately. 请记住,这将立即停止循环。 If you just want to "hide" empty results try something like this 如果您只想“隐藏”空结果,请尝试这样的操作

while($cat = mysql_fetch_assoc($categories)) 
{
   if ( $cat['category'])            
   echo "<a href='#'>" . $cat['category'] . "</a><br>";
}

Use BREAK to get out of the while loop. 使用BREAK退出while循环。 I am confused though. 我很困惑。 If the query doesn't return anything, you wouldn't be looping anyway, right? 如果查询不返回任何内容,那么您就不会循环,对吗?

EDIT 编辑

It sounds like you might be looping through a set of company_id's in your page and then getting categories for each, right? 听起来您可能正在页面中遍历一组company_id,然后获取每个类别的类别,对吗?

foreach ($list_companies as $cid)
{
   LOAD CATEGORIES for $cid
   while (have categories)
   {
     echo link to it
   }
}

If that's right, then break will get you out of your inner while and onto the next company but, again, if there are no categories, then there's nothing to break out of. 如果这是正确的,那么休息会让您脱离内心而进入下一家公司,但是同样,如果没有类别,则没有任何休息的机会。

I would not encourage break 'ing out of the loop, you should be checking that there are rows returned with mysql_num_rows() before passing to the loop. 我不鼓励break循环,您应该在传递到循环之前检查是否有mysql_num_rows()返回的行。

<?php
if(isset($cid)){
    $categories = mysql_query('SELECT distinct(category),id FROM products WHERE company_id = ' . $cid );
    if(mysql_num_rows($categories)>=1){
        while($cat = mysql_fetch_assoc($categories)){
            echo "<a href='#'>" . $cat['category'] . "</a><br>";
        }
    }
}
?>

One of the easiest ways that always works is the die() function 始终有效的最简单方法之一是die()函数

if(empty($var)) {
    die();
}

or you can add an error message 或者您可以添加错误消息

die("No results found!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM