yiven

PHP与mysql这对黄金搭档配合的相当默契,但偶尔也会遇到一些小需求不知道该怎么做,例如今天要谈到的:如何判断sql语句查询的结果集是否为空!

我们以查询学生信息为例,来看看究竟如何实现我们的需求。

首先,来看看我们的数据表“student”中所存储的数据是个什么样子;

id  stuname  gender  age  grade  class

1  张三     男    16  17    3

2  李四     男    15  18    2

3  王美丽    女    16  17    5

我们来看看sql查询功能代码,我们要将年龄为16岁的学生信息都查出来;

<?php
$sql = "select * from `student` where `age`=\'16\';";
$rows = mysql_query($rs);
?>
<ul>
    <?php
        while($rows=mysql_fetch_array($rs)){
    ?>
        <li>姓名:<?php echo $rows[\'stuname\'];?></li>
        <li>性别:<?php echo $rows[\'gender\'];?></li>
        <li>年龄:<?php echo $rows[\'age\'];?></li>
        <li>年级:<?php echo $rows[\'grade\'];?></li>
        <li>班级:<?php echo $rows[\'class\'];?></li>
    <?php
        }
    ?>
</ul>

 

以上便是查询功能,当结果集不为空时,一切正常,当数据集为空时,会得到一个空白的ul标签

作为使用者却不知道为什么没有得到数据,此时我们需要给用户一个提示信息,那么我们就需要判断这个结果集是否为空!

如何才能判断结果集是否为空呢,有下面两个方法:

<?php
//方法一 获取select结果集的行数
$rows=mysql_query("select * from `student` where `age`=\'16\';");
if (mysql_num_rows($rows) < 1){
echo \'查询无数据!\';
}

//方法二 返回上一次操作受影响的行数
$rows=mysql_query("select * from `student` where `age`=\'16\';");
if(!mysql_affected_rows()){
    echo \'查询无数据!\';
}
?>

知道了方法,那么把方法套到我们的代码中看看效果吧

//方法一
<?php
$sql = "select * from `student` where `age`=\'16\';";
$rows = mysql_query($rs);
?>
<ul>
    <?php
    if (mysql_num_rows($rs) < 1){
        echo \'查询无数据!\';
    }else{
        while($rows=mysql_fetch_array($rs)){
    ?>
        <li>姓名:<?php echo $rows[\'stuname\'];?></li>
        <li>性别:<?php echo $rows[\'gender\'];?></li>
        <li>年龄:<?php echo $rows[\'age\'];?></li>
        <li>年级:<?php echo $rows[\'grade\'];?></li>
        <li>班级:<?php echo $rows[\'class\'];?></li>
    <?php
        }
    }
    ?>
</ul>

//方法二
<?php
$sql = "select * from `student` where `age`=\'16\';";
$rows = mysql_query($rs);
?>
<ul>
    <?php
    if(mysql_affected_rows()){
        while ($rows=mysql_fetch_assoc($rs)){
    ?>
        <li>姓名:<?php echo $rows[\'stuname\'];?></li>
        <li>性别:<?php echo $rows[\'gender\'];?></li>
        <li>年龄:<?php echo $rows[\'age\'];?></li>
        <li>年级:<?php echo $rows[\'grade\'];?></li>
        <li>班级:<?php echo $rows[\'class\'];?></li>
    <?php
        }
    }else {
        echo "查无数据!";
    }
    ?>
</ul>

OK,大功告成,现在查不到数据的时候就会有提示了哦!

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-08-21
  • 2022-12-23
  • 2021-11-05
  • 2022-01-28
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-09-23
  • 2022-12-23
  • 2021-05-07
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
相关资源
相似解决方案