当我使用下面的表单更新数据库中的数据时,会显示错误跟随错误。我该如何解决这个错误?
Cannot add or update a child row: a foreign key constraint fails
(`nov-cms`.`faqs_cat`, CONSTRAINT `faqs_cat_ibfk_20` FOREIGN KEY (`id`)
REFERENCES `tblfaqs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)'
形式:
function editpage_($editid) {
$conn = Doctrine_Manager::connection();
$data['headingtop'] = "FAQ'S > FAQ'S > Edit FAQ'S";
$data['title_faqs'] = "Edit FAQ's";
$data['errormess'] = '';
$title_faqs = addslashes($this->input->post('title_faqs'));
$content = addslashes($this->input->post('editor1'));
$seo_description = addslashes($this->input->post('seo_description'));
$category = $this->input->post('category'); //print_r($category['cate']); exit;
$isActive = $this->input->post('isactive');
$position = $this->input->post('position');
$qryDel2 = $conn->prepare("DELETE from faqs_cat where id='$editid'");
$qryDel2->execute();
$query = $conn->prepare("UPDATE tblfaqs SET title_faqs='$title_faqs',content='$content',isActive='$isActive',position='$position',seo_description='$seo_description' WHERE id='$editid' ");
$query->execute();
$id = $conn->lastInsertId();
//when we add a page this insert a record to table, and this is id of record inserted.. this is a function default of mysql, we use to get last insert id to insert this to orther table...
foreach ($category as $data) {
$query = $conn->prepare("insert into faqs_cat (fc_id, id, category_id) values ('','$id','$data')"); //in this.
$query->execute();
}
$url = 'admin/faqs/';
echo'
<script>
window.location.href = "' . base_url() . $url . '";
</script>
';
答案 0 :(得分:0)
错误在这一行:
$id = $conn->lastInsertId();
具体而言,$id
仍为空,因为lastInsertId()
未返回值。这会导致约束失败,因为在插入faqs_cat
时需要ID。
如果您尝试从数据库中获取自动生成的密钥,则可能需要为lastInsertId
指定一个序列名称,具体取决于您要连接的数据库类型(对于例如,Postgres需要一个序列名称)。尝试创建一个名为&#39; mySequence&#39;的序列。而是使用它:
$id = $conn->lastInsertId('mySequence');