0

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?

4

2 回答 2

1

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;
于 2013-04-29T04:51:23.113 回答
0

请注意,您要交换引号:使用 " 表示 PHP 字符串,使用 ' 表示 SQL 字符串。首先,它与 PostgreSQL 和其他检查此类内容的数据库系统不兼容。

否则,正如 Christopher 告诉您的,您可以在查询中测试作物标识符。仅当您在 PHP 中的 '...' 之间定义一个字符串时,这些变量才不会在字符串中被替换。所以他显示了错误的 PHP 代码。

"SELECT ... $somevar ..."

会工作得更好。

然而,编写这样的字符串存在一个安全问题:这是非常危险的,因为 $somevar 可能代表一些额外的 SQL 并完全将您的 SELECT 转换为您甚至不想考虑的东西。因此,Christopher 提到的 Active Record 更安全。

于 2013-04-29T05:00:40.810 回答