Search code examples
phpinheritancemysqliresultset

How to extend mysqli_result and add new method


Mysqli_result class has fetch_all() method returning multiple rows from result set at once in form of an array of rows (actually that's 2-dimensional array because rows already are arrays of fields). Also a result set has method fetch_object() returning a single row in form of an object.

Now I'd like to extend mysqli_result class and add new method fetch_objects() (plural) which would return an associative array of objects where association key is record ID [id=>Object()]. Of course, I'll need to extend mysqli class too and override its query() method in order to return my extended result set. But I don't get how the transfer of connection and query parameter between mysqli and returned mysqli_result is made.

This should work this way:

$db=new ReallyMySQLi(...); //initiating my mysqli

$myrst=$db->query($SQL); //returned my extended result

//fetch_objects() returning associative array of objects
//with record ID as associative key
foreach($myrst->fetch_objects() as $id=>$object)
{
  echo 'Customer ID:'.$id; //or $object->id;
  echo 'Customer firstname:'.$object->firstname;
  echo 'Customer lastname:'.$object->lastname;
}

Solution

  • I found this on the PHP manual of mysqli_result and tinkered some. I didn't try though.

    class Database_MySQLi extends MySQLi
    {
        public function query($query)
        {
            $this->real_query($query);
            return new Database_MySQLi_Result($this);
        }
    }
    
    class Database_MySQLi_Result extends MySQLi_Result
    {
        public function fetch_objects()
        {
            $rows = array();
            while($row = $this->fetch_object())
            {
                $rows[$row->id] = $row;
            }
            return $rows;
        }
    }
    

    And the usage would be

    $db=new Database_MySQLi(...); //initiating my mysqli
    
    $myrst=$db->query($SQL); //returned my extended result
    
    //fetch_objects() returning associative array of objects
    //with record ID as associative key
    foreach($myrst->fetch_objects() as $id=>$object)
    {
      echo 'Customer ID:'.$id; //or $object->id;
      echo 'Customer firstname:'.$object->firstname;
      echo 'Customer lastname:'.$object->lastname;
    }