Mysqli_result类有fetch_all()
方法以行数组的形式从结果集中一次返回多行(实际上这是二维数组,因为行已经是字段数组)。此外,结果集的方法fetch_object()
以对象的形式返回单行。
现在我想扩展mysqli_result类并添加新方法fetch_objects()
(复数),它将返回一个关联对象数组,其中关联键是记录ID [id => Object()]。当然,我还需要扩展mysqli类并覆盖其query()方法以返回扩展结果集。但我不知道如何在mysqli和返回的mysqli_result之间传递连接和查询参数。
这应该是这样的:
$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;
}
答案 0 :(得分:1)
我在mysqli_result的PHP手册中找到了这个并且修改了一些。我没试过。
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;
}
}
用法是
$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;
}
答案 1 :(得分:-1)
抱歉,我从未使用mysqli作为mysql驱动程序两年。但是我为你做了这个建议。
你可以选择PDO,PDO就像多重数据库驱动程序一样酷。
就像laravel雄辩,学说都以PDO为基础。
$pdo = new PDO('sqlite:db.sqlite');
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
祝你好运!