Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter Select Query

I have a simple CodeIgniter Active record query to select an ID:

$q = $this -> db
           -> select('id')
           -> where('email', $email)
           -> limit(1)
           -> get('users');

How can I assign the above ID to a variable (eg. $id) For example,

echo "ID is" . $id;

Thanks.

like image 608
Roman Avatar asked Jun 20 '11 07:06

Roman


1 Answers

Thats quite simple. For example, here is a random code of mine:

function news_get_by_id ( $news_id )
{

    $this->db->select('*');
    $this->db->select("DATE_FORMAT( date, '%d.%m.%Y' ) as date_human",  FALSE );
    $this->db->select("DATE_FORMAT( date, '%H:%i') as time_human",      FALSE );


    $this->db->from('news');

    $this->db->where('news_id', $news_id );


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

    if ( $query->num_rows() > 0 )
    {
        $row = $query->row_array();
        return $row;
    }

}   

This will return the "row" you selected as an array so you can access it like:

$array = news_get_by_id ( 1 );
echo $array['date_human'];

I also would strongly advise, not to chain the query like you do. Always have them separately like in my code, which is clearly a lot easier to read.

Please also note that if you specify the table name in from(), you call the get() function without a parameter.

If you did not understand, feel free to ask :)

like image 196
Herr Avatar answered Oct 20 '22 22:10

Herr