简体   繁体   中英

PHP Conditional Syntax Help If/Else?

I need the proper php syntax to handle a situation with my website's breadcrum links for product pages. All of my items are derived from a MySQL database.

The inventory items are organized either by itemCategory or itemAuthor. Not all items have an itemCategory associated with them so in the database they are NULL. All items however, have an itemAuthor.

What I basically want to say is:

If the item has a value for itemCategory, echo the itemCategory. If itemCategory is NULL, echo itemAuthor instead.

Thanks for any help.

if(empty($itemCategory)) {
  echo $itemAuthor;
} else {
  echo $itemCategory;
}

The mysql solution:

SELECT ...
    IFNULL(`itemCategory`, `itemAuthor`) AS `itemCategory`
FROM ...

In PHP You just echo itemCategory. No additional conditions. If it was NULL id database, it will be itemAuthor in PHP.

The php solution:

if ($r['itemCategory']):
    echo $r['itemCategory'];
else:
    echo $r['itemAuthor'];
endif;

The NULL is returned as empty string. It is converted to php false in if expressions.

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