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();
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With