简体   繁体   中英

PHP / SQL if null do something else something else

I would like to check if a particular value in a table is set to null so as to echo information accordingly. I would like that if the $row['GeneralID'] is set to null a particular code is printed, and if not another is printed, as this would affect the way things are displayed.

function responsive_menu($sql) {
    include 'connect.php';
    $result = $conn->query($sql);
    if ($result->num_rows > 0);
    $current_album = "";

    echo "<div id='responsive_menu'>\n<div id='show_menu'>\n<img src='media/images/show-menu-icon.png' alt='menu_icon'/>\n</div>\n<div id='cssmenu'>\n<ul>\n";  
    while ($row = $result->fetch_assoc()) {
        if ($current_album <> "" && $current_album <> $row['pageID']) {
            if ($row['GeneralID'] <> NULL) {
                echo "</ul></li>\n";  
            }
            else {
            echo "";  
            }
        }
        if ($current_album <> $row['pageID']) {
            if ($row['GeneralID'] <> NULL) {
                echo "<li class='has-sub'><a href='".$row['pageURL']."?pageID=".$row['pageID']."'><span>".$row['page_name']."</span></a>\n<ul>\n";  
            }
            else {
            echo "<li><a href='".$row['pageURL']."?pageID=".$row['pageID']."'><span>".$row['page_name']."</span></a>\n</li>\n";  
            }
        $current_album = $row['pageID'];
        }
        if ($row['GeneralID'] == NULL) {
            echo "";
        } else {        
        echo "<li><a href='info.php?pageID=".$row['pageID']."&infoID=".$row['GeneralID']."'><span>".$row['general_name']."</span></a></li>\n";
        }
    }
    echo "</ul>\n</div>\n</div>\n";
    $conn->close();
}

Here is the resulting code on top and the way the code should be displayed at the bottom: http://jsfiddle.net/yevfc1rw/

You need 3 equal signs:

if( $row['GeneralID'] === NULL ) //do stuff

PHP treats NULL, false, 0, and the empty string as equal when using 2 equal signs.

3 signs will ensure to check type and value

The <> operator is not valid in PHP, you should use != instead, but nevertheless PHP has a function for checking if a value is null, is_null() . Therefore instead of $row['GeneralID'] <> NULL you should use;

!is_null($row['GeneralID'])

ie, $row['GeneralID'] is not null. The ! means NOT.

Or for checking for the varible is null, instead of $row['GeneralID'] == NULL ;

is_null($row['GeneralID'])

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