首页 > 解决方案 > 数据未插入数据库

问题描述

我正在尝试将此数据插入我的表中,但由于某种原因,它没有被插入,我不确定我需要做什么来解决这个问题。

控制器:

    public function insert_comments()
{
    $userID = $this->session->userdata('username');
    $data['user_id'] = $this->Review_Model->getUserID($userID);
    $data['review_id'] = get_cookie('ReviewID');
    $data['comments'] = $this->input->post('comments');

    //using the function in the model insert the comments,reviewID,userID
    $this->Review_Model->insert_comments($data);

}

模型:

public function insert_comments($data)
    {
        $this->db->insert('comments',$data);

    }

function getUserID($username)
{
    $this->db->select('user_id');
    $this->db->from('users');
    $this->db->where('username = ' . $username);
    $query = $this->db->get();

    return $query->result();
}

桌子:

桌子

标签: codeigniter

解决方案


这是我的建议

连接到数据库(如果您忘记了)

class Review_Model extends CI_Model {
   public function __construct(){
      parent::__construct();
      $this->load->database();
   }

在您的代码中,getUserID函数返回一个结果对象。不值user_id。因此,您应该进行以下更改。

function getUserID($username)
{
    $this->db->select('user_id');
    $this->db->from('users');
    $this->db->where('username', $username);
    $query = $this->db->get();

    return $query->result()->user_id;
}

现在它将返回user_id,而不是对象。

抱歉英语不好。


推荐阅读