简体   繁体   中英

if isset not working properly with database fetch

So I am fetching some information from my database using this query.

$fetch_menu = $db->prepare("SELECT id, title, link, custom_link, rel FROM header_menu ORDER BY id DESC");
$fetch_menu->execute();

$header_menu = $fetch_menu->fetchAll();
$header_count = $fetch_menu->rowCount();

Now I am trying to use this statement to echo out data from my database.

$nav_count = 0;
while ($header_count > $nav_count){
    echo "<li><a ";

    if (isset($header_menu[$nav_count]['rel'])){
        echo "rel='";
        echo $header_menu[$nav_count]['rel'];
        echo "'";
    }
    $nav_count ++;
}

Now, the problem occurs on my website where I get this output (from a field WITHOUT rel filled or custom_url filled):

<a rel="" href="">Contact</a>

The column with rel is empty in my Database, but it still echoes. I have the exact same problem with this statement, where the custom_link field is filled in 1 of the menu items, but not the rest.

if (isset($header_menu[$nav_count]['custom_link'])){
    echo " href='";
    echo $header_menu[$nav_count]['custom_link'];
}
else if (isset($header_menu[$nav_count]['link'])){
    echo " href='/";
    echo $header_menu[$nav_count]['link'];
}

The output from the field filled with a custom_url is this:

<a rel="" href="http://example.com">Test page</a>

Why can't I use isset on my database fetch?

you can use var_dump($header_menu); to see what's in the variable.

also use empty() instead of isset()

In case you use mysqli, as you indicate it with the tag, fetchAll works like mysqli_fetch_row and it sets the variable to the corresponding value returned by the query, but 'sets NULL fields to the PHP NULL value'. So (as others point it out in their comments) the variable is always set, but note that its value can be NULL.

isset determines if 'a variable is set and is not NULL'. So actually, you can use isset, to determine if the query returns NULL for a field. But this is not your case, you have an empty string and you can use empty to check that. Note, that you don't need to combine empty with isset: 'a variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.'

In your case:

isset($header_menu[$nav_count]['rel']) // true, unless rel is NULL in the database
$header_menu[$nav_count]['rel'] == "" // true if rel is an empty string ("") in the database, false otherwise
empty($header_menu[$nav_count]['rel']) // true if rel is an empty string, "0" (as a string), 0, 0.0, FALSE or NULL in the database, false otherwise

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