<?php
$mysqli = new mysqli("localhost","root","","ims");
if (mysqli_connect_errno()){
    die('Unable to connect!'). mysqli_connect_error();
}
if(isset($_POST['searchuserid'])){
$id = $_POST["rolename"];
$sql = "select * from `t_userinfo` where u_id='$id'";
$result = $mysqli->query($sql);
}
?>在页面最上面是如上的代码,当点击button时执行sql,这个时候我得到了一个$result。
然后我在下面的html里面写
<?php 
    
    while($row = $result->fetch_array()){?>
     <tr>
            <td><?php echo $row["u_id"]?></td>
            <td><?php echo $row["u_name"]?></td>
            <td><?php if ($row["u_state"] == 1){
                echo "正在使用";
            }else if ($row["u_state"] == 0){
                echo "该编号已过期";};?></td>
            <td>
                  <a href="edit.html">编辑</a>
                  <a href="">删除</a>
                  <a href="">详细</a>
            </td>
        </tr><?php } ?>这个时候,页面可以执行,也可以正确的查询到数据,但是页面会打印出一个致命的错误,Fatal error: Call to a member function fetch_array() on a non-object in index.php on line 66我理解是未查询前$result这里应该有个判断,因为查询后这个错误就没了!但是思考了很久不知道该如何做,是要判断$result是不是一个对象吗?

解决方案 »

  1.   

    $row = $result->fetch_array()这个我放在上面的if里面就可以,不出现任何错误,但是在下面的while的时候带入$row就会重复执行!
    如下:<?php
    $mysqli = new mysqli("localhost","root","","ims");
    if (mysqli_connect_errno()){
        die('Unable to connect!'). mysqli_connect_error();
    }
    if(isset($_POST['searchuserid'])){
        $id = $_POST["rolename"];
        $sql = "select * from `t_userinfo` where u_id='$id'";
        $result = $mysqli->query($sql); 
        $row = $result->fetch_array()
    }
    ?>
    这样下面的html里面的while($row)就会反复的执行,这个我明白是什么原因!但是跟开始说的一样,如果把$row = $result->fetch_array()放在while里又会出错!
      

  2.   

    <?php foreach($row as $val):?>
             <tr>
                <td><?php echo $val["u_id"]?></td>
                <td><?php echo $val["u_name"]?></td>
                <td><?php if ($val["u_state"] == 1){
                    echo "正在使用";
                }else if ($val["u_state"] == 0){
                    echo "该编号已过期";};?></td>
                <td>
                      <a href="edit.html">编辑</a>
                      <a href="">删除</a>
                      <a href="">详细</a>
                </td>
            </tr>
    <?php endforeach;?>
      

  3.   

    使用前应检查
    if(is_a($result, 'mysqli_result')) {
      ....
    }仅判断是否为对象(is_object)也可以,但是不严密一般的说,你应该总是执行查询,这样就没有问题了
    $sql = "select * from `t_userinfo` where 1=1"; //查询全部数据
    //$sql = "select * from `t_userinfo` where 1=2"; //什么也查不到
     
     if(isset($_POST['searchuserid'])){
        $id = $_POST["rolename"];
        $sql = "select * from `t_userinfo` where u_id='$id'";
    }
    $result = $mysqli->query($sql); 
    while($row = $result->fetch_array()) {
      ....
    }
      

  4.   

    谢谢各位的解答,maohuitao1992已经在QQ替我找到原因了!