Search code examples
phpmysqlsmarty

How to Solve this Warning: mysqli_fetch_assoc() expect s parameter 1 to be mysqli_result, How to solve this


In below code it produces a Warning while execute. Warning: mysqli_fetch_assoc() expect s parameter 1 to be mysqli_result, How to solve this?

<?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>

Thankyou for all good answers.


Solution

  • It's because $record = $db->fetchAll() is returning a string (either success or error) and not the mysql resource.

    Consider changing the Conn Class to:

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

    Now the fetchAll() method will return a mysqli_result on a successful query, or 'error' if not

    In my opinion, this is not the best way to handle errors. Consider looking into try/catch blocks and how you can "throw" errors from the class up the stack.