CodeIgniter插入自动增量

Pig*_*let -1 php mysql codeigniter

我正在为工作做一个基本的添加用户表单,我正在尝试将用户添加到数据库但是当我尝试时,我只是得到主键是重复错误.很确定解决方案是正确的看着我,但我今天碰壁了大声笑.

数据库表struture

dbo.ci_users

id(PK, int, not null)
user_name(nchar255, not null)
user_email(nchar255, not null)
user_password(nchar255, not null)
user_displayname(nchar255, not null)
user_active(smallint, not null)
user_level(smallint, not null)
Run Code Online (Sandbox Code Playgroud)

Adduser_model

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class adduser_database extends CI_Model {

         function __construct()
        {
            // Call the Model constructor
            parent::__construct();
            $this->load->database();
        }

    public function insert_into_db()
    {
        $data = array(
            'id'            => '0',
            'user_active'        => '1',
            'user_level'         => '2',
            'user_displayname'   => $this->input->post('user_displayname'),
            'user_email'         => $this->input->post('user_email'),
            'user_name'      => $this->input->post('user_name'),
            'user_password'      => $this->input->post('user_password') 
        );

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

    }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*nde 6

您指定的主键值对于所有插入都是相同的.这就是你得到那个错误的原因.删除该行代码并让MySQL为您指定该值,因为AUTO_INCREMENT意味着MySQL会自动为每个插入分配下一个值:

$data = array(
    'id'          => '0', // <-- REMOVE THIS
    'user_active' => '1',
Run Code Online (Sandbox Code Playgroud)

编辑

您似乎忘了将AUTO_INCREMENT添加到表中.此代码修复:

ALTER TABLE ci_users CHANGE id id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY;
Run Code Online (Sandbox Code Playgroud)