我如何在mysql或php中更新此代码?

时间:2016-03-03 12:26:26

标签: php mysql database foreign-keys

我有两个数据库表

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_newsarticles,CONSTRAINT fk_ArtCat FOREIGN KEY(id_c)参考categoryid_c))

1 个答案:

答案 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
  1. 类别表
  2. 中没有id_k字段
  3. name是一个文本字段,但$ cat不包含在单引号中
  4. $catid = "SELECT id_k FROM category WHERE name = $cat";

    1. $ catid是一个sql命令,但你用单引号括起它的值,使它成为一个字符串。您实际上是在尝试将sql命令作为文本插入到类别ID中,这将失败。
    2. 我的建议是将提交类别的表单更改为此脚本以发送类别ID而不是类别名称,因此您不必根据类别名称进行反向查找以获取ID。