questionable questionable - 1 month ago 6
MySQL Question

Get a single value from a result set returned from PHP codeigniter model

I am working on PHPStorm with a codeigniter framework and the MVC architecture.
I need a function in my model that would query the

sysuser
table in my database and return the
uid
(User Id) when the username is passed.

sysuser Table structure

+---------------+----------------+-----------------+
| uid | name | username |
+---------------+----------------+-----------------+
| 1 | kim | kcdla |
+---------------+----------------+-----------------+
| 2 | Sam | sammyG |
+---------------+----------------+-----------------+


In my function, if I pass, for example, the username
kcdla
I need to retrieve the
uid
as
1
so that I can store this to a variable as
$uid
and return it to another function that will use it. But currently the result is an array and when I tried to access only the first cell from the array, I get an Exception.

Code in Context

public function getUserUid($username)
{
$this->db->select("*");
$this->db->from('sysuser');
$this->db->where('username',$username);
$query = $this->db->get();
$tableArray = $query->result();
foreach ($tableArray as $row) {
$uid = $row->uid;
}
return $uid;
}


I need to use the
$uid
value returned from this method within another method as shown below.

public function getUserDetails($username)
{
$uid = $this->userModel->getUserUid($username);
$this->db->select("*");
$this->db->from('userProfile');
$this->db->where('uid',$uid);
$query = $this->db->get();
return $query->result();

}


Any suggestions in this regard will be highly appreciated.

Answer

Try this. As you need single row based on username, you have to use row()(returns Object) or row_array() (returns array) instead of result() because result() or result_array() returns result set

public function getUserUid($username)
{
    $this->db->select("*");
    $this->db->from('sysuser');
    $this->db->where('username',$username);
    $query = $this->db->get();
    $row  = $query->row();
    return $row->uid;
}
Comments