发生数据库错误列'title'不能为null

时间:2017-02-22 11:53:46

标签: php codeigniter

这是我的site_model代码 从数据库获取所有数据并使用Html表单将数据插入数据库 请帮助我不知道我哪里弄错了

class Site_model extends CI_Model
{
    public function __construct()
    {
    }

    // get all data from database
    public function get_records()
    {
        $query = $this->db->get('user_data');
        return $query->result();
    }    

    // add records into database by form
    public function add_record($formData)
    {
        $this->db->insert('user_data', $formData);
    }
}

比我将模型加载到控制器并获取数组中的值。并在创建一个数组后将表单值发送到数据库

class Site extends CI_Controller
{
    var $data = array();

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Site_model');
    }

    public function index()
    {
        //get data into array from model
        $data = $this->data;
        $data['user_info'] = $this->Site_model->get_records();

        // get data from html form and send to database
        $formData = array(
            'title' => $this->input->post('post_title'),
            'description' => $this->input->post('post_descrip')
            );

        // send record to model
        $this->Site_model->add_record($formData);
        $this->load->view('crud_viw', $data);
    }
}

我的观看代码看起来像这样

<!DOCTYPE html>
<html>
<head>
    <title>Crud</title>
</head>
<body>

    // Html form to send values to database
    <form method="post">
        <input type="text" placeholder="Title" name="post_title"></input>
        <input type="text" placeholder="Description" name="post_descrip">       </input>
        <button type="submit">Submit</button>
    </from>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

更改索引方法如下。您只需在发布事件时输入数据

public function index()
    {
        //get data into array from model
        $data = $this->data;
        $data['user_info'] = $this->Site_model->get_records();
        if($this->input->post()){  //<--- add this condition

        // get data from html form and send to database
        $formData = array(
            'title' => $this->input->post('post_title'),
            'description' => $this->input->post('post_descrip')
            );

        // send record to model
        $this->Site_model->add_record($formData);
       }
        $this->load->view('crud_viw', $data);
    }

答案 1 :(得分:0)

在您的数据库中,您的列“title”应该不为null ..所以在数据库中将“title”标记为not null 希望它有所帮助..

答案 2 :(得分:0)

阻止获取a database error occurred column 'title' cannot be null的简单方法是使用三元运算符(?:)。如果你没有发布值,它将插入空字符串。

 $formData = array(
            'title' => isset($this->input->post('post_title'))?$this->input->post('post_title'):" ",
            'description' => isset($this->input->post('post_descrip'))?$this->input->post('post_descrip'):" "
            );

希望它有效。