0

我尝试使用 sql 为我的 CI 执行一次选项更新三个表,但为什么它仍然错误?

这是错误警告:

A Database Error Occurred

Error Number: 1062

Duplicate entry '0' for key 1

UPDATE `t_publisher` SET `id_publisher` = NULL, `publisher` = NULL, `artis` = NULL, `id_label` = NULL WHERE `id_publisher` = '113'

这是代码:

function update($id_user=null)
  {
   if (($this->input->post('submit') == 'Update')){
    $user=$this->input->post('username');
    $pass=$this->input->post('userpassword');
    $ussta=$this->input->post('userstatus');
    $usty=$this->input->post('usertype');

   $data = array(
    'user_name' => $user,
    'user_pass' => $pass,
    'user_status' => $ussta,
    'user_type' => $usty);

    $this->db->where('user_id', $this->input->post('id'), $data);
    $this->db->update("t_user",$data);

   $data1 = array(
    'id_publisher' => $id_publis,
    'publisher' => $publis,
    'artis' => $ar,
    'id_label' => $id_lab);

    $this->db->where('id_publisher', $this->input->post('id'), $data);
    $this->db->update("t_publisher",$data1);
    echo $this->db->last_query();
    die();

   $data2 = array(
    'id_label' => $id_lab,
    'label' => $label);

    $this->db->where('id_label', $this->input->post('id'), $data);
    $this->db->update("t_label",$data2);
    echo $this->db->last_query();
    die();
    redirect("registrasi/reg");
   }
    $var['data'] = $this->db->query("select * from t_user where USER_ID= '$id_user'")->row_array();  
    $var1['data'] = $this->db->query("select * from t_publisher where id_publisher = '$id_publis'")->row_array();
    $var2['data'] = $this->db->query("select * from t_label where id_label = '$id_lab'")->row_array();
    $this->load->view('update', $var,$var1,$var2);
}

我的代码有什么问题?请帮忙。之前谢谢。

4

1 回答 1

2

您的UPDATE子句将id_publisher列设置为NULL,并且根据列的名称和您收到的错误,列是PRIMARY KEY设置为的表unsigned NOT NULL

因此,当您这样做时id_publisher = NULL,MySQL 会将其转换为id_publisher = 0由于unsigned部分。这将在第一次执行时很好,但是,当您在第二行上运行它时,您现在将尝试插入第二个主键值0,这是不允许的。

根据die()示例代码中语句的位置,我假设以下块是罪魁祸首:

   $data1 = array(
    'id_publisher' => $id_publis,
    'publisher' => $publis,
    'artis' => $ar,
    'id_label' => $id_lab);

    $this->db->where('id_publisher', $this->input->post('id'), $data);
    $this->db->update("t_publisher",$data1);

在这里,您的$id_publis变量为空或 null。

我建议要么id_publisher = NULL从子句中删除与从数组UPDATE中删除一样简单的部分,要么重新考虑您实际需要将其设置为开头的原因(在这种情况下,删除该行会更有益吗?)'id_publisher' => $id_publis,$data1null

于 2012-11-12T03:25:28.863 回答