Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 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 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...