Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

sql - Returning one cell from Codeigniter Query

I want to query a table and only need one cell returned. Right now the only way I can think to do it is:

 $query = $this->db->query('SELECT id FROM crops WHERE name = "wheat"');
 if ($query->num_rows() > 0) {
     $row = $query->row();
     $crop_id = $row->id;
 }

What I want is, since I'm select 'id' anyway, for that to be the result. IE: $query = 'cropId'.

Any ideas? Is this even possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Of course it's possible. Just use AND in your query:

$query = $this->db->query('SELECT id FROM crops WHERE name = "wheat" AND id = {$cropId}');

Or you could use the raw power of the provided Active Record class:

$this->db->select('id');
$this->db->from('crops');
$this->db->where('name','wheat');
$this->db->where('id',$cropId);
$query = $this->db->get();

If you just want the cropId from the whole column:

foreach ($query->result()->id as $cropId)
{
    echo $cropId;
}

Try this out, I'm not sure if it will work:

$cropId = $query->first_row()->id;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...