I have two tables with records. In the first table, I am displaying personal information and in the second table, I am adding the activities details.
Now I am trying to display the record using joins. So below code, I am using in the model
public function getMemberActivity($gotMemberId){
$getDetails = array('members.member_id'=>$gotMemberId,'member_activity.activity_status'=>1,'members.is_Approved'=>1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id','LEFT')
->get()
->result();
//echo $this->db->last_query();
//print_r($result);
if($result)
{
return $result;
}
else
{
return 0;
}
}
Controller
Note: I am getting multiple member id here because I have above some more logic; that's the reason I am using for each.
$ActivityData=[];
foreach ($data['getAllMember'] as $key => $m_id) {
$ActivityData[] = $this->Access_model->getMemberActivity($m_id->member_id);
}
$data['MemberActivity'] = $ActivityData;
Now if I found the records related the member id in the secondary table then I am getting the output but if not found a record in the second table then I am getting the error Message: Invalid argument supplied for foreach()
If I remove 'member_activity.activity_status'=>1 from the where clause then my join query is working. I mean I am getting the member records.
->join('member_activity', 'members.member_id = member_activity.member_id','LEFT')
View
$SActivity=$MemberActivity;
//print_r($SActivity);
if($SActivity){
foreach ($SActivity as $sec_1) {
foreach ($sec_1 as $sec_activities) {
//list here
}
}
}
else{echo"no data available";}
So my expected output is, I have to display the records if found in the second table if not found then also display the member table records. How can I solve this problem?
The problem is with your model function getMemberActivity. If there is no record then you returns 0 and when you foreach you will get error because its not an array. So you can simply return $result since codeigniter return default array.
public function getMemberActivity($gotMemberId)
{
$getDetails = array('members.member_id' => $gotMemberId, 'members.is_Approved' => 1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id AND member_activity.activity_status = 1', 'LEFT')
->get()
->result();
return $result;
}
Second option is you can check !empty before your foreach.