如何解决这个警告:mysqli_fetch_assoc()期望s参数1是mysqli_result,如何解决这个问题

时间:2017-01-14 06:21:53

标签: php mysql smarty

在下面的代码中,它会在执行时产生警告。警告:mysqli_fetch_assoc()期望s参数1为mysqli_result,如何解决?

<?php
    require '../smarty3/libs/Smarty.class.php';
    $smarty = new Smarty;
    class conn
    {
               public $conn = '';
               public function fetchAll()
                {
                    $sql = "SELECT * FROM test" ;
                    if(mysqli_query($this->conn,$sql))
                    {   return 'success'; }
                else{   return 'error'; }
                }
    }
    $db = new conn();
    $record = $db->fetchAll();
    if($record != 'error'){
        while($row = mysqli_fetch_assoc($record))
        {
            header('location : view.tpl');
        }
    }else{  echo "No Records Found";}
    $smarty->display('view.tpl');
    ?>
    **View.tpl**
    <table align = "center">
        {section name = i loop = $row}
            <tr> <td> {$smarty.section.i.rownum} </td>
                 <td> {$row[i].name} </td>
                 <td> {$row[i].country} </td>
            </tr>
        {/section}
    </table>

谢谢你们所有的好答案。

1 个答案:

答案 0 :(得分:0)

因为$record = $db->fetchAll()正在返回一个字符串(successerror)而不是mysql资源。

考虑将Conn类更改为:

    class conn
        {
                   public $conn = '';
                   public function fetchAll()
                    {
                        $sql = "SELECT * FROM test" ;
                        $r = mysqli_query($this->conn,$sql)
                        if($r)
                        {   
                         return $r; }
                    else{   return 'error'; }
                    }
        }

现在,fetchAll()方法会在成功查询时返回mysqli_result,如果不是,则'error'

在我看来,这不是处理错误的最佳方法。考虑一下try / catch块以及如何&#34; throw&#34;来自班级的错误。