Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all objects without loop in OOP MySQLi

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 using the following snippet 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? Is there something like:

$image = $result->fetch_object(((s)))

So then my code would look like:

$result = $db->query("...");
$comments = $result->fetch_objects();
like image 994
oaziz Avatar asked Jan 06 '12 08:01

oaziz


2 Answers

The mysqli_result class provides a fetch_all method to collect the full result set. However, that method will only return associative or numeric arrays (or a hybrid), not objects.

like image 176
pilcrow Avatar answered Nov 17 '22 23:11

pilcrow


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);
like image 41
Kyle Noland Avatar answered Oct 06 '22 01:10

Kyle Noland