简体   繁体   中英

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

In my page I have multiple 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

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. 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?

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.

<?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

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

or you can add an error message

die("No results found!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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