php函数不返回foreach中MySQL查询的所有结果
嘿,伙计们,我对从MySQL数据库检索数据的函数有点问题,然后我用foreach循环迭代结果,检查一个值是否为null,如果为null,用另一个值替换它 这个函数的问题是,返回数据后,我只能查看从数据库检索到的一条记录。可能是一些简单的事情,但我无法理解 我希望在将其传递给控制器或视图之前执行此操作。也许这在foreach循环中是不可能的?我错过了什么 下面是我的代码示例php函数不返回foreach中MySQL查询的所有结果,php,mysql,foreach,return-value,Php,Mysql,Foreach,Return Value,嘿,伙计们,我对从MySQL数据库检索数据的函数有点问题,然后我用foreach循环迭代结果,检查一个值是否为null,如果为null,用另一个值替换它 这个函数的问题是,返回数据后,我只能查看从数据库检索到的一条记录。可能是一些简单的事情,但我无法理解 我希望在将其传递给控制器或视图之前执行此操作。也许这在foreach循环中是不可能的?我错过了什么 下面是我的代码示例 public function get_basic_user_data(){ $sql = 'SELECT Acco
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\u数据。试试这个
$new_data = new stdClass
...
$all_data[] = $new_data;
不必检查代码中的null值,您可以在SQL查询中使用IFNULL语句,这会稍微分离逻辑,但在这种情况下可能值得这样做。函数只返回结果中的最后一行,因为新的\u数据变量在循环的每个步骤中都会被覆盖。在函数开始时将新的_数据声明为数组,并将行添加为数组元素
...
$new_data[] = new stdClass;
...
foreach的每次迭代都会覆盖$new_数据,因此最终当函数返回时,只会返回最后获取的行。要返回多行,可以将所有行存储在一个数组中,然后在最后返回该数组。它看起来像这样:
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;
}
要使用此函数,您必须更改使用它在对象数组中循环的代码。Awesome!非常感谢,这非常有效!lol应该知道这很简单。