使用 MySQL 中的外键将数据插入 table

Inserting data into a table using foreign keys in MySQL

我正在尝试使用 mysql 中的外键将数据插入联系人 table,table 的结构如下

CONTACTS TABLE

id   contactname   phone_number   fk_id
USERS TABLE

pers_id   username   email   securecode

联系人table中的fk_id是FOREIGN KEY,它与用户table中的pers_id PRIMARY KEY有关, 我正在尝试在用户 table

中插入与用户相关的新联系人

一切都在 PHP 和 MySQl 中完成。我在代码中使用了下面显示的 sql 语句,但它不起作用

   $name = $_GET['contactname'];
   $number = $_GET['phone_number'];
   $username = $_GET['username'];

   $sql = "INSERT INTO contacts SET contactname='$name', phone_number='$number',fk_id=(select pers_id 
  from users where username='$username')";
   $result = mysqli_query($conn, $sql);

希望有人能帮忙

您可以使用 insert ... select:

insert into contacts(contactname, phone_number, fk_id)
select :contactname, :phone_number, pers_id
from users u
where username = :username

为了使其正常工作,username 应该是 users table 中的唯一键。

你也可以这样表达:

insert into contacts(contactname, phone_number, fk_id)
values (
    :contactname, 
    :phone_number, 
    (select pers_id from users u where username = :username)
);

请注意,我重写了语句以使用正确的参数。 从不 将来自程序外部的数据连接到查询字符串中:这会打开您的代码 SQL 注入。推荐阅读:How can I prevent SQL injection in PHP?.