2016-04-17 24 views
1

我想根據用戶id獲取用戶ip地址。我不明白爲什麼它不起作用。如何在sql查詢中獲取單個元素?

在控制器:

function block_user($name,$user_id) 
{ 
    $ip = $this->m_db->get_ips($user_id); 
    $data = array(
    'username' => $name , 
    'ip' => $ip , 
    ); 
$this->db->insert('blacklist', $data); 

$this->db->where('user_id',$user_id); 
$this->db->delete('comments'); 
$this->index(); 
} 

在模型:

function get_ips($user_id) 
{ 
    $this->db->select('ip'); 
    $this->db->from('users'); 
    $this->db->where('user_id',$user_id); 
    $query = $this->db->get(); 
    return $query; 
} 

回答

1

CodeIgniter - return only one row?

你應該做的是返回一行

function get_ips($user_id) 
{ 
    $this->db->select('ip'); 
    $this->db->from('users'); 
    $this->db->where('user_id',$user_id); 
    $query = $this->db->get(); 
    $ret = $query->row(); 
    return $ret->ip; 
} 
0

首先,你必須讓所有的事務數據庫在模型中,那麼你需要使用

$this->db->get(); 

正確的方法是: Controller.php這樣

function block_user($name,$user_id){ 
    $re = $this->m_db->get_ips($user_id, $name); 

    echo $re; 
} 

model.php

function insert_data($ip, $name){ 
    $data = array(
        'username' => $name , 
        'ip'  => $ip , 
       ); 

    $this->db->insert('blacklist', $data); 

    $this->db->where('user_id',$user_id); 
    $this->db->delete('comments'); 

    return $this->db->affected_rows(); 
} 

function get_ips($user_id, $name){ 
    $this->db->select('ip'); 
    $this->db->from('users'); 
    $this->db->where('user_id',$user_id); 
    $query = $this->db->get()->row(); 

    $resp = $this->insert_data($query, $name); 

    return $resp; 
}