CodeIgniter插入自动增量

时间:2016-08-17 12:02:34

标签: php mysql codeigniter

我正在为工作做一个基本的添加用户表单,我试图将用户添加到数据库但是当我尝试时,我只是得到主键是重复错误。非常确定解决方案是正确地看着我,但我今天碰到了一堵墙lol。

数据库表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)

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);

    }
}

2 个答案:

答案 0 :(得分:6)

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

$data = array(
    'id'          => '0', // <-- REMOVE THIS
    'user_active' => '1',

修改

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

ALTER TABLE ci_users CHANGE id id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY;

答案 1 :(得分:0)

First of all you have to change in database and make AUTO_INCREMENT id then use the following code. It will helps you 

public function insert_into_db()
{
    $data = array(

        '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);