【问题标题】:getting a value from a resultset with Codeigniter使用 Codeigniter 从结果集中获取值
【发布时间】:2012-12-07 00:04:29
【问题描述】:

在我的模型中,我有这个 sn-p

$this->db->select('*');
        $this->db->from('User');
        $this->db->where('email', $mail);
        $query = $this->db->get();

        return $query;

据我所知,$query 是一个数组(一组结果),我想检索该数组中某个字段的特定值以将其返回或将其分配给另一个变量,问题是如何?

我想做这样的事情

$value = $query['first_field_of_resultset'];
return $value;

【问题讨论】:

  • $query 实际上有一个CI_DB_mysql_result 对象,您可以在该对象上调用方法来返回结果,结果存储在result_object 属性中。
  • 我该如何使用它的方法?

标签: php mysql codeigniter activerecord


【解决方案1】:

延长约翰的回答,你需要保护自己,以防万一没有回来 所以在你的模型方法中:

// make sure we have a result
if ( $query->num_rows() == 1 ) 
{  
// assign the result 
$user = $query->row();  
// pull out the field you want 
$value = $user->first_field_of_resultset;
// return it
return $value ; 
}
else { return FALSE; }

然后在你的控制器中,说如果模型被称为 user_model

if(! $value = $this->user_model->getUser($email) )
{
 // boo hoo no results
} 
else
{
// success
}

当然,这假设您已经通过 CI 表单验证运行 $email 以确保它是有效的电子邮件 - 在发送到您的数据库之前。

【讨论】:

    【解决方案2】:

    a bunch of different ways to get the results。这是一个:

    $user = $query->row(); 
    echo $user->first_field_of_resultset;
    

    如果你更喜欢数组:

    $user = $query->row_array();
    echo $user['first_field_of_resultset'];
    

    【讨论】:

      【解决方案3】:

      如果你想要第一行,你可以这样做:

      $row = $query->first_row();
      

      但是如果您只需要一列,我不知道您为什么要重新搜索所有字段:

      $this->db->select('user.the_column_to_select');
      

      【讨论】:

        【解决方案4】:

        $query 是一个对象。因此,为了将结果作为数组获取,您需要执行以下操作。

        $result = $query->result_array();
        return $result[0];
        

        【讨论】:

          【解决方案5】:

          你也可以试试这个:

          $email = $this->db->select('email')->from('users')->where(array(
                'userID' => $userID))->limit(1)->get()->row('email');
          
          // $email will either be the email address you're looking for or FALSE
          

          【讨论】:

            猜你喜欢
            • 2017-02-24
            • 1970-01-01
            • 2012-08-11
            • 2017-11-05
            • 2022-01-03
            • 1970-01-01
            • 1970-01-01
            • 2020-01-30
            • 1970-01-01
            相关资源
            最近更新 更多