我尝试使用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);
}
我的代码有什么问题?请帮忙。谢谢。
答案 0 :(得分:2)
您的UPDATE
子句将id_publisher
列设置为NULL
,并根据列名称和您收到的错误 >列是表格PRIMARY KEY
,其设置为unsigned NOT NULL
。
因此,当您执行id_publisher = NULL
时,由于id_publisher = 0
部分,MySQL会将其转换为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
变量为空或空。
我建议您删除id_publisher = NULL
子句中的UPDATE
部分,这与从'id_publisher' => $id_publis,
数组中删除$data1
一样简单,或重新考虑您实际的原因需要将其设置为null
以开始(在这种情况下,删除行会更有益吗?)