简体   繁体   中英

A condition using if else statement in php

I have a small problem here. I need to make a condition in my page, if no data were found in database, a message should be outputted

this is the code

foreach ($movies as $movie)
{
    $movie_id = $movie['movie_id'];
    $movie_name = $movie['movie_name'];
    $movie_category = $movie['movie_category'];
    $movie_display = $movie['movie_display'];

    if ($movie_id){
        echo '<tr>';
        echo '<td>' . $movie_name . '</td>';
        echo '<td>' . $movie_category . '</td>';
        echo '<td align="center">';
        if ($movie_display==1) { echo "YES";} else { echo "NO";} 
        echo '</td>';
        echo '<td align="center">';
        echo "<a href='editmovies.php?movie_id={$movie_id}'>". edit .'</a><br/></td>';
        echo '<td align="center">';
        echo "<a class='delete' href='deletemovie.php?movie_id={$movie_id}'>". delete .'</a><br/></td>';
        echo '</tr>';
    }
    else { 
        echo 'no results were found';
    }
}
echo '</table>';

Even when the database is empty, no message is delivered and I dont know why.

Thank you

Your message is inside your foreach loop so if no items are found, that part of the code is never reached.

You need to add an additional check before or after the loop:

if (empty($movies))
{
  echo 'no results were found';
}
else
{
  // do you loop
}

This should work just fine.

if(count($movies) > 0){
    foreach ($movies as $movie)
        // Do stuff
    }
}
else{
    echo 'No results returned';
}

You're assuming that the array $movies will have a $movie . You should instead check to see if the array is empty:

if( empty($array) ) {
    //Array empty
}
else {
    foreach ...
}

代替if($movie_id) { ... }尝试if (!empty($movie_id)) { ... }

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