Reputation: 915
I'm trying to get first name and last name of registered users. This is my getfirstname , getlastname function in the model
public function getf()
{
$email = $this->input->post('email');
$this->db->where('email', $this->input->post('email'));
$query = $this->db->get('users');
if($query->num_rows == 1)
{
$row = $query->row();
echo $row->fname;
}
}
public function getl()
{
$this->db->where('email', $this->input->post('email'));
$query = $this->db->get('users');
if($query->num_rows == 1)
{
$row = $query->row();
echo $row->lname;
}
}
In My Contoller:
public function members()
{
if($this->session->userdata('is_logged_in'))
{
$data['fname'] = $this->getf();
$data['lname'] = $this->getl();
$this->load->view('members', $data);
}
else
{
redirect('main/restricted');
}
}
Im echoing the fname and lname variables in my view which prints 'Array' and not actual firstname and lastname
echo $fname;
echo $lname;
Upvotes: 0
Views: 26741
Reputation: 19882
Your call to model is totally wrong and you are not following the standard procedure. Try it like this. Seperate the logics
Controller
public function members()
{
if($this->session->userdata('is_logged_in'))
{
$email = $this->input->post('email');
$result = $this->mymodel->getnames($email);
if($result){
$data['fname'] = $result->first_name;
$data['lname'] = $result->last_name;
$this->load->view('members', $data);
}
}
else
{
redirect('main/restricted');
}
}
And create single function for model not two functions for two values that could be retrieved with single function Also return the object instead of echoing
public function getnames($email)
{
$this->db->where('email',$email);
$query = $this->db->get('users');
if($query->num_rows == 1)
{
return $query->row();
}
return false;
}
Upvotes: 4
Reputation:
UserModel
class UserModel extends CI_Model
{
public function getItemByEmail($email)
{
// check email
$this->load->helper('email');
if( ! $email OR ! valid_email($email))
return array();
$this->db->where('email', $email);
$this->db->limit(1);
$item = $this->db->get('users')->row();
return $item;
}
}
Controller:
public function members()
{
if( ! $this->session->userdata('is_logged_in'))
redirect('main/restricted');
$this->load->model('UserModel');
$this->load->view('members', array(
'userRow' => $this->UserModel->getItemByEmail($this->input->post('email', TRUE))
));
}
View:
<?= (isset($userRow->fname) ? $userRow->fname : ''); ?>
Upvotes: 0
Reputation: 123
From what I can see you haven't actually declared the 'fname' and 'lname' variables, unless I've missed it, but if it keeps returning 'Array' then it is because you need to serialise the array with
$variable = json_encode($arrayName);
This will turn the array into a string, hope this helps.
Upvotes: 0