問題描述
伙計們,我有一個從 MySQL 數(shù)據(jù)庫中檢索數(shù)據(jù)的函數(shù)的小問題,然后我用 foreach 循環(huán)迭代結(jié)果,檢查一個值以查看它是否為空,如果是,則將其替換為另一個價值.
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.
這個函數(shù)的問題在于,在返回數(shù)據(jù)后,我只能查看從數(shù)據(jù)庫中檢索到的一條記錄.可能是一些簡單的事情,但它超出了我的范圍.
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.
我想在將其傳遞給控制器??或視圖之前執(zhí)行此操作.也許這對于 foreach 循環(huán)是不可能的?我錯過了什么?
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!
推薦答案
此時您只是返回最后一行數(shù)據(jù).像這樣更改代碼以從該函數(shù)返回所有行的數(shù)組:
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;
這樣,從數(shù)據(jù)庫返回的每一行都將添加到名為 $rows
的數(shù)組中.最后你必須返回你的新數(shù)組.
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.
這篇關(guān)于php函數(shù)沒有從foreach中的MySQL查詢返回所有結(jié)果的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!