【问题标题】:Codeigniter $this->db->get(), how do I return values for a specific row?Codeigniter $this->db->get(),我如何返回特定行的值?
【发布时间】:2012-01-22 09:36:32
【问题描述】:

假设我有一个包含三列的数据库表:ID、名称和年龄。 我需要找到具有特定(唯一)ID 的用户,然后返回年龄。目前,我正在使用以下代码

$this->db->where('id', '3');
$q = $this->db->get('my_users_table');

如何获取该用户的年龄?我想我必须使用

$q->result()

但不确定如何将它与一行一起使用。

【问题讨论】:

标签: php sql codeigniter


【解决方案1】:

解决方案一

$this->db->where('id', '3');
// here we select every column of the table
$q = $this->db->get('my_users_table');
$data = $q->result_array();

echo($data[0]['age']);

解决方案二

// here we select just the age column
$this->db->select('age');
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
$data = $q->result_array();

echo($data[0]['age']);

解决方案三

$this->db->select('age');
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
// if id is unique, we want to return just one row
$data = array_shift($q->result_array());

echo($data['age']);

解决方案四(无有效记录)

$q = $this->db->query('SELECT age FROM my_users_table WHERE id = ?',array(3));
$data = array_shift($q->result_array());
echo($data['age']);

【讨论】:

  • 谢谢,它有效 :) 有没有更有效的方法来做到这一点?
  • 对于这样一个简单的查询,纯 SQL 可能是更直接的选择,无论如何我认为这 4 种情况之间我并没有太大变化
【解决方案2】:

你可以使用 row() 代替 result()。

$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();

【讨论】:

    【解决方案3】:

    访问单行

    //Result as an Object
    $result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row();
    echo $result->age;
    
    //Result as an Array
    $result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row_array();
    echo $result['age'];
    

    【讨论】:

      【解决方案4】:

      如果您动态获取数据,例如,当您需要基于用户登录的数据时,请考虑使用以下无活动记录的代码示例:

       $this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));
      
       return $query->row_array();
      

      这将根据您设置的用户会话数据返回特定行。

      【讨论】:

        【解决方案5】:

        您只需在一行中使用它。

        $query = $this->db->get_where('mytable',array('id'=>'3'));
        

        【讨论】:

          猜你喜欢
          • 2012-07-23
          • 1970-01-01
          • 2016-01-30
          • 1970-01-01
          • 2017-04-10
          • 2015-04-16
          • 2016-05-22
          • 2016-12-29
          • 2012-05-14
          相关资源
          最近更新 更多