Get all objects without loop in OOP MySQLi

别说谁变了你拦得住时间么 提交于 2020-01-10 05:06:42

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/8755325/get-all-objects-without-loop-in-oop-mysqli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!