PHP使用函数查找学生记录

时间:2015-11-10 12:08:28

标签: php mysql

  • 表:学生
    enter image description here

  • student.php

    <?php
    function findStudentRecord()
    {
          //Db connection
    
          $q1 = "select * from student where gender = 'F'";
          $r1 = mysqli_query($dbc, $q1);
          $total_records = mysqli_num_rows($r1);
    
          $record = array();
          if($total_records > 0)
          {
              while($row1 = mysqli_fetch_array($r1, MYSQLI_ASSOC))
              {
                  $record[] = $row1;
              }
          }
          else
          {
              //[HERE]
          }
    
          return $record;
    }
    
    $record = findStudentRecord();
    //[HERE]
    ?>
    
  • 我想查找女生记录,但我的数据库中没有记录。如何从函数返回0值并显示&#34;未找到记录&#34;在[HERE]部分的网页上?

2 个答案:

答案 0 :(得分:2)

if($total_records > 0)

不添加其他块,所以它会返回一个空数组,现在你可以做这样的事情

$records = findStudentRecord();
if(count($records) === 0) {
    echo "No record found";
}

答案 1 :(得分:2)

我不会改变你的功能。它返回一个数组(可能是空的),无论如何都是非常一致的。

而是查看返回的数组项数:

$record = findStudentRecord();
//[HERE]
if(count($record) == 0) {
  echo "No record found";
} else {
  // what ever
}