如何确定while循环在php中是否从db返回任何内容?

时间:2015-12-11 15:21:10

标签: php mysql

我想知道如何确定从MySQL检索数据的while循环不返回任何内容。这是我的代码,请看一下:

    <?php 
function getAdmins(){
    global $con;
    global $id;
    $get_admin = "select * from admins where id != $id";
    $run_admin = mysqli_query($con,$get_admin);
    while($row_admin = mysqli_fetch_array($run_admin)){
        $id_admin = $row_admin['id'];
        $username_admin = $row_admin['username'];
        $fname_admin = $row_admin['fname'];
        $lname_admin = $row_admin['lname'];
        $email_admin = $row_admin['email'];
        echo '....';
            }
}

5 个答案:

答案 0 :(得分:2)

在输入while循环之前设置$loopExecuted = false; 然后在循环集$loopExecuted = true;内 在循环之后,您可以检查变量以查看是否至少有一次while循环迭代。

答案 1 :(得分:1)

使用mysqli_num_rows($ run_admin)计算行数;

<?php 

function getAdmins(){
    global $con;
    global $id;
    $get_admin = "select * from admins where id != $id";
    $run_admin = mysqli_query($con,$get_admin);

    if (mysqli_num_rows($run_admin) > 0) {

      while($row_admin = mysqli_fetch_array($run_admin)){
          $id_admin = $row_admin['id'];
          $username_admin = $row_admin['username'];
          $fname_admin = $row_admin['fname'];
          $lname_admin = $row_admin['lname'];
          $email_admin = $row_admin['email'];
          echo '....';
              }

         }
    } else {
       echo 'empty data';
     }

}

答案 2 :(得分:0)

$results = array();

while($row_admin = mysqli_fetch_array($run_admin)){
    results[] = $row_admin;
}

if (empty($results)) {
    echo 'Empty, no results';
}

答案 3 :(得分:0)

检测您找到的行数。

$get_admin = "select * from admins where id != $id";
$run_admin = mysqli_query($con, $get_admin);

// Count of rows found
$num_rows = mysqli_num_rows($run_admin);

if($num_rows > 0){
    while($row_admin = mysqli_fetch_array($run_admin)){
        $id_admin = $row_admin['id'];
        $username_admin = $row_admin['username'];
        $fname_admin = $row_admin['fname'];
        $lname_admin = $row_admin['lname'];
        $email_admin = $row_admin['email'];
        echo '....';
    }
}
else{
    // Nothing returned
}

答案 4 :(得分:0)

$ run_admin只是一个mysqli_result对象,如果没有返回任何内容,它将为空...

所以我们可以使用以下

if(empty($run_admin))
{
    //Nothing returned
}

或者,mysqli_num_rows()基本上做同样的事情,但明确地查看mysqli_result对象的$num_rows属性

if(mysqli_num_rows($run_admin) == 0)
{
    //Nothing returned
}

后者可能更清晰,因为很明显我们会说&#34;如果没有任何回复&#34;而不是&#34;如果没有结果&#34; - 虽然两者的结果是相同的,但如果有人稍后读取代码,则mysqli_num_rows会更具描述性。