[英]php function not returning all results from a MySQL query in a foreach
大家好,我对从MySQL数据库检索数据的函数有一个小问题,然后使用foreach循环遍历结果,检查一个值是否为空,如果为空,则将其替换为另一个值。
此功能的问题在于,返回数据后,我只能查看从数据库检索到的一条记录。 可能很简单,但超出了我。
我想先将其传递给控制器或视图。 也许这对于foreach循环是不可能的? 我想念什么?
这是我的代码示例。
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;
}
希望有人可以帮助我吗? 谢谢!
目前,您只是返回最后一个数据行。 像这样更改代码,以从该函数返回所有行的数组:
$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
的数组中。 最后,您必须返回新数组。
您每次迭代都覆盖$ new_data。 尝试这个
$new_data = new stdClass
...
$all_data[] = $new_data;
您可以只在SQL查询中使用IFNULL语句,而不用检查代码中的空值,这确实将逻辑分开了一点,但是在这种情况下可能是值得的。
该函数仅返回结果的最后一行,因为new_data变量在循环的每个步骤中都被覆盖。 在函数的开头声明new_data一个数组,并将行添加为数组元素
...
$new_data[] = new stdClass;
...
foreach的每次迭代都会覆盖$ new_data,因此最后函数返回时,将仅返回最后获取的行。 要返回多个行,可以将所有行存储在一个数组中,然后最后返回该数组。 它看起来像这样:
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);
$data = 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;
$data[] = $new_data;
}
return $data;
}
为了能够使用此功能,您必须更改使用该功能循环遍历对象数组的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.