沃梦达 / 编程问答 / php问题 / 正文

php函数没有从foreach中的MySQL查询返回所有结果

php function not returning all results from a MySQL query in a foreach(php函数没有从foreach中的MySQL查询返回所有结果)

本文介绍了php函数没有从foreach中的MySQL查询返回所有结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我有一个从 MySQL 数据库中检索数据的函数的小问题,然后我用 foreach 循环迭代结果,检查一个值以查看它是否为空,如果是,则将其替换为另一个价值.

Hey guys I have a little issue with a function that retrieves data from a MySQL Database and then I iterate over the results with a foreach loop, checking a value to see if it is null and if it is, replacing it with another value.

这个函数的问题在于,在返回数据后,我只能查看从数据库中检索到的一条记录.可能是一些简单的事情,但它超出了我的范围.

The problem with this function is this, that after returning the data I'm only able to view one record retrieved from the database. Probably something simple but it's beyond me.

我想在将其传递给控制器​​或视图之前执行此操作.也许这对于 foreach 循环是不可能的?我错过了什么?

I would like to do this before passing it to the controller or view. Maybe this isn't possible with the foreach loop? What am I missing?

这是我的代码示例.

public function get_basic_user_data(){
    $sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url 
            FROM Account 
            LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id 
            AND Profile_Photos.Active = 1
            WHERE Account.idAccount != ?';
    $account_id = $this->get_account_id();
    $data = $this->db->query($sql, $account_id);

    foreach($data->result() as $row){

            if($row->Thumb_Url == NULL){
                $image = base_url().'assets/images/no_photo_thumb.png';
            }else{
                $image = $row->Thumb_Url; 
            }


    $new_data = new stdClass;
    $new_data->First_Name = $row->First_Name;
    $new_data->Last_Name = $row->Last_Name;
    $new_data->User_Name = $row->User_Name;
    $new_data->Thumb_Url = $image;

    }   

    return $new_data;

}   

希望有人能帮我解决这个问题吗?谢谢!

Hopefully someone can help me with this? Thanks!

推荐答案

此时您只是返回最后一行数据.像这样更改代码以从该函数返回所有行的数组:

At the moment you are just returning the last data row. Change your code like this to return an array of all your rows from that function:

$rows = array()
foreach($data->result() as $row){

    if($row->Thumb_Url == NULL){
        $image = base_url().'assets/images/no_photo_thumb.png';
    }else{
        $image = $row->Thumb_Url; 
    }


    $new_data = new stdClass;
    $new_data->First_Name = $row->First_Name;
    $new_data->Last_Name = $row->Last_Name;
    $new_data->User_Name = $row->User_Name;
    $new_data->Thumb_Url = $image;

    $rows[] = $new_data;
}   

return $rows;

这样,从数据库返回的每一行都将添加到名为 $rows 的数组中.最后你必须返回你的新数组.

This way every row returned from the database will be added to an array named $rows. At the end you have to return your new array.

这篇关于php函数没有从foreach中的MySQL查询返回所有结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:php函数没有从foreach中的MySQL查询返回所有结果

基础教程推荐