【问题标题】:$this->db->insert_id(); returning 0 every time in codeigniter [duplicate]$this->db->insert_id();每次在codeigniter中返回0 [重复]
【发布时间】:2015-12-15 19:43:15
【问题描述】:

我正在使用 codeigniter 并一次插入一条记录。但问题是 $this->db->insert_id();每次都返回 0,但是记录已成功创建。我无法弄清楚。这是常见的情况还是我犯了一些愚蠢的错误。我使用 email_id 作为主键,使用 mobile no 作为唯一键。

这是我的模态代码:

function signup_insert($data) {

        $result = $this->db->insert('registration_detail', $data);
        $insert_id = $this->db->insert_id();
        return $insert_id;
    }

这是我的控制器代码:

function insert_signup() {
        $email = $this->input->get('email');
        $name = $this->input->get('name');
        $password1 = $this->input->get('password1');
        $password2 = $this->input->get('password2');
        $phone = $this->input->get('phone');
        $country = $this->input->get('country');

        $data = array(
            'email' => $email,
            'name' => $name,
            'pwd' => $password1,
            'phone' => $phone,
            'country' => $country
        );

        $insert_id = $this->signup->signup_insert($data);
        print_r($insert_id);
    }

【问题讨论】:

  • 我刚做了,每次还是返回0。
  • 您使用的是什么数据库? MySQL?
  • 对,就是 $db['default']['dbdriver'] = 'mysql';
  • signup_insert()中打印insert id,你就知道是生成了不返回还是根本没有生成
  • 这一定是你的mysql有问题,因为mysql的insert_id()使用了mysql_insert_id函数。你有 AUTO_INCREMENT 行吗?

标签: php mysql codeigniter


【解决方案1】:

要返回一个 id 它应该有一个 AUTO_INCREMENT 列。如果不是,则无法返回 insert_id,请参阅此处的 mysql 文档..

https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

【讨论】:

    【解决方案2】:

    因此$this->db->insert_id()

    执行数据库插入时的插入ID号。

    而且您的数据库中没有自动递增的 id

    检查数据是插入还是不使用

    $this->db->affected_rows()
    

    在执行“写入”类型查询时显示受影响的行数 (插入、更新等)。

    模型

    function signup_insert($data) {
        $result = $this->db->insert('registration_detail', $data);
        $rows =  $this->db->affected_rows();
        if($rows>0){
        return $rows;
        }else{
          return FALSE;
        }
    }
    

    阅读http://www.codeigniter.com/user_guide/database/helpers.html

    【讨论】:

    • 简短说明:在 CodeIgniter4 中,它的 affectedRows() 而不是affected_rows()。
    猜你喜欢
    • 2016-12-29
    • 1970-01-01
    • 2011-10-20
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2012-07-23
    • 1970-01-01
    相关资源
    最近更新 更多