7

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();
2
  • 1
    You can make your loop shorter if you use a bodyless for loop. for (; $obj = $result->fetch_object(); $arr_objects[] = $obj); Commented Aug 18, 2022 at 20:38
  • Related: How to fetch all list of object records Commented Aug 18, 2022 at 20:54

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

It's not possible to get an array of objects using mysqli_fetch_all(). The available options are: indexed array, associative array, or both.

Consider using the PHP Data Objects (PDO) interface, which has many more fetch modes and is thus superior to MySQLi in that regard.

1 Comment

Very diplomatic. It's superior to mysqli in all regards, IMHO. Unless similarity to the old mysql extension is something you value.
-1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.