我有两个数据库表
CREATE TABLE `articles` (
`id_a` int(11) not null,
`name` varchar(70) not null,
`text` text not null,
`datum` timestamp not null,
`id_c` int(11) not null,
`id_u` int(11) not null )
ENGINE=InnoDB;
和
CREATE TABLE `category` (
`id_c` int(11) not null,
`name` varchar(70) not null )
ENGINE=InnoDB;
我在那里有一个实现
ALTER TABLE `articles`
ADD CONSTRAINT `fk_ArtCat`
FOREIGN KEY (`id_c`)
REFERENCES `category` (`id_c`);
将文章插入数据库的代码
$name = $_POST['name'];
$text = mysqli_real_escape_string ($connect, $_POST['edit']);
$cat = $_POST['category'];
$catid = "SELECT id_c FROM category WHERE name = $cat";
$sql = "INSERT INTO articles (id_a, name, text, datum, id_c, id_u) VALUES ('', '$name', '$text', current_timestamp, '$catid', '1')";
你能告诉我为什么在试图发表文章时出现错误吗? 这个错误我认为:
无法添加或更新子行:外键约束失败(db_news
。articles
,CONSTRAINT fk_ArtCat
FOREIGN KEY(id_c
)参考category
(id_c
))
答案 0 :(得分:0)
你的php / sql代码存在很多问题。
CREATE PROCEDURE proc_name(param1,param2,param3)
AS
BEGIN
BEGIN TRAN
;WITH cte(col1, col2, col3)
AS
(
SELECT col1
,col2
,col3
FROM table1
)
UPDATE table2
SET col1 = 'text'
FROM table2 INNER JOIN cte ON cte.hmy = table2.hmy
WHERE some condition
COMMIT TRAN
-- UPDATE will run but not part of the transaction.
UPDATE table3
SET date = ''
FROM table3 INNER JOIN cte ON cte.hmy = table3.hmy
WHERE some different condition
END
$catid = "SELECT id_k FROM category WHERE name = $cat";
我的建议是将提交类别的表单更改为此脚本以发送类别ID而不是类别名称,因此您不必根据类别名称进行反向查找以获取ID。