codeigniter从数据库查询不能按预期工作

时间:2015-10-25 08:22:17

标签: php codeigniter

使用CI,似乎某些东西被挤压了。

$this->db->where('email', $username);
$query = $this->db->get('users'); //to check if user already registered.
if($query->num_rows == 1)
{
    return false;
}else{
    $this->db->insert('users', array('email' => $username, 'password' => $password));
    return true;
}

但每次都需要控制else

这里是print_r($query);转储

CI_DB_mysqli_result Object ( [conn_id] => mysqli Object ( [affected_rows] => 1 [client_info] => mysqlnd 5.0.8-dev - 20102224 - $Id: 731e5b87ba42146a687c29995d2dfd8b4e40b325 $ [client_version] => 50008 [connect_errno] => 0 [connect_error] => [errno] => 0 [error] => [field_count] => 5 [host_info] => localhost via TCP/IP [info] => [insert_id] => 0 [server_info] => 5.6.25 [server_version] => 50625 [stat] => Uptime: 167005 Threads: 1 Questions: 2022 Slow queries: 0 Opens: 76 Flush tables: 1 Open tables: 64 Queries per second avg: 0.012 [sqlstate] => 00000 [protocol_version] => 10 [thread_id] => 192 [warning_count] => 0 ) [result_id] => mysqli_result Object ( [current_field] => 0 [field_count] => 5 [lengths] => [num_rows] => 1 [type] => 0 ) [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0 [num_rows] => [row_data] => )

并显示错误 A Database Error Occurred ,而不是返回false

Error Number: 1062

Duplicate entry 'email@provider.com' for key 'email'

1 个答案:

答案 0 :(得分:1)

num_rows是方法而非属性。试试这个

$this->db->where('email', $username);
$query = $this->db->get('users'); //to check if user already registered.
if($query->num_rows() == 1)
{
    //if found
}else{
    //if not found
}