简体   繁体   中英

Codeigniter Assign Database Value to Variable

I am getting the following error

A PHP Error was encountered

Severity: 4096

Message: Object of class stdClass could not be converted to string

When trying to do the following

So I have a users table which has a "privileged" column. If this column is set to 1 then the user is a "privileged user" if it is set to 0 then they are not.

This value is specified by my account registration form.

What I want to do is set a variable in codeigniter which is 1 if the user is privliged and 0 if they are not.

What I have been trying is the following;

In my Model i have the following;

 public function get_privileged($user_id){
    // $this->db->where('user_id',$id);
    // $this->db->select('privileged');
    // $query = $this->db->get('users');
    $query = $this->db->select('privileged')->from('users')->where('id',$user_id)->get();
    return $query->row();

}

**In my View I have the following **

<?php $user_id = $this->session->userdata('user_id');?>
<?php $status =  $this->user_model->get_privileged($user_id);?>
<?php var_dump($status);?>

I have just been trying to echo the result first in my controller so I know if it is working, the end goal is to assign the value to a variable for example the variable $status.

The result of the var dump is

object(stdClass)#27 (1) { ["privileged"]=> string(1) "0" } 

Note that the value of 0 is correct for that user

I want to set a variable to zero if this returns a zero from the db or set the variable to 1 if this returns a 1 from the db.

How can I do this, I have followed all the codeigniter documentation but get no where, I am new to this.

I believe the issue was it was returning an object not a string.

Two get the value which I wanted I used the following echo $status->privileged;

Well the problem is that you are returning row when you need just value of that row.

My suggestion is to use this:

    $result = $this->db->query($query);

    if ($result->num_rows() == 1){ //When I need just one value in case I check if there is just one row.
        return $result->row(0)->privileged;
    }else{
        return false;
    }   

or just this:

$result = $this->db->query($query); 

return result->row(0)->privileged;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM