简体   繁体   English

在PHP中使用if else语句的条件

[英]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. 您的消息在foreach循环内,因此如果找不到任何项目,则永远不会到达该部分代码。

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 . 您假设数组$movies将具有$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)) { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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