【问题标题】:How to only update last inserted record in PHP Codeigniter?如何只更新 PHP Codeigniter 中最后插入的记录?
【发布时间】:2015-08-11 10:30:08
【问题描述】:

我正在尝试更新 codeigniter 中最后插入的记录。我有一个桌子经销商,我有姓名、电话、国家代码、余额和 key 等字段。现在这个键是其他信息的组合,比如他的名字、电话和国家代码。所以我首先插入用户信息并保留关键字段 NUll 完成后我想更新记录并通过连接字段来插入键。我已成功生成密钥(连接),但我的代码更新了表中的所有记录,而不是我想更新最后插入的记录。所以我不能填写最初为空的关键字段。 下面是我的控制器代码:

public function edit ($id = NULL)
{
    // Fetch a user or set a new one
    if ($id) {
        $this->data['user'] = $this->reseller_m->get($id);
        count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
    }
    else {
        $this->data['user'] = $this->reseller_m->get_new();
    }

    // Set up the form
    $rules = $this->reseller_m->rules_admin;
    $id || $rules['password']['rules'] .= '|required';
    $this->form_validation->set_rules($rules);

    // Process the form
    if ($this->form_validation->run() == TRUE) {

        $data = $this->reseller_m->array_from_post(array('sip_username','sip_password','key','allocation_block','name','email','password','phone','balance','user_num','address','country','created','modified','status'));

        $data['password'] = $this->reseller_m->hash($data['password']);

        $key=$this->reseller_m->save($data, $id);

        for($i=1; $i<=$data['user_num'];$i++)
        {
            $userdata=array('key'=>$key);
            // here users is taken name of user table with retailer_id is field
            $this->user_m->save($userdata,$id);
         }

         $values=array($this->input->post('name'),$this->input->post('country'),$this->input->post('name'));

         $key=implode('-',$values);


        $this->db->update('reseller' ,array('key'=>$key));
        redirect('admin/reseller');
    }

    // Load the view
    $this->data['subview'] = 'admin/reseller/edit';
    $this->load->view('admin/_layout_main', $this->data);
}

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    正在更新所有记录,因为您没有使用任何约束。

    要获取最后插入记录的id,可以使用

    $last_id = $this->db->insert_id();
    

    然后使用更新

    $this->db->where('<your_pk_field>',$last_id);
    $this->db->update('reseller', array('key'=>$key));
    

    希望这会有所帮助。

    【讨论】:

    • 但是如果他使用查询执行插入,您将不会获得插入 ID
    • 这里的 是什么?
    • “经销商”表中的主键字段。
    • 我在插入第二条记录时插入了一条记录,其中我有密钥 jack-usa-jack,我收到错误截断不正确的 DOUBLE 值:'jack-usa-jack'
    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    相关资源
    最近更新 更多