Get all objects without loop in OOP MySQLi

2019-02-23 00:08发布

This is how I get one record with MySQLi:

$result = $db->query("...");
$image = $result->fetch_object();

Now I need to get the comments and pass it to the view. I'm doing this right now but it doesn't seem right:

$result = $db->query("...");

while ($row = $result->fetch_object())
    $comments[] = $row;

I'm wondering if there's a way to remove the loop? Something like have $image = $result->fetch_object(((s))), so my code would look like:

$result = $db->query("...");
$comments = $result->fetch_objects();

标签: php mysql mysqli
2条回答
闹够了就滚
2楼-- · 2019-02-23 00:16

Yes. The mysqli_result class provides a fetch_all method to do this. However, that method will only return associative or numeric arrays (or a hybrid), not objects.

查看更多
姐就是有狂的资本
3楼-- · 2019-02-23 00:37

Without seeing your SQL, it's tough to say. There may be a better query you could use. Post your SQL and I'll take another look.

In terms of your SQL query, if your query returns multiple rows, then you have already fetched them with one db call.

I don't see a way to collect into an array all of the comments, but you can clean up your code with a custom function.

function get_all_rows_as_array(&$result)
{
    foreach($result as mysql_fetch_assoc($result))
    {
        $array[] = $row;
    }

    return $array;
}

$result = $db->query("...");
$comments = get_all_rows_as_array($result);
查看更多
登录 后发表回答