如何使用 html 形式和 php 将数据插入带有外键的 table?

How to insert data into table with foreign key using html form and php?

情况:用户登录后想通过html表单保存自己喜欢的颜色。但是在 phpMyAdmin 中我可以看到外键和主键(它们是两个单独的 table 中的列 'user_id')不匹配。外键在有数据的行中显示NULL,而主键在有数据的行中显示数字(例如3)。

如前所述,有 2 个 table:(用户和颜色)

以下 sql 用于创建 table 颜色:

CREATE TABLE colors ( 
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
favorite_color TEXT NOT NULL, 
user_id INT, 
FOREIGN KEY (user_id) REFERENCES users(user_id) 
); 

以下sql用于创建table个用户:

CREATE TABLE users (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

从用户插入数据的页面是welcome.php,它包含以下代码:

<?php
session_start();
    
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login");
    exit;
}
?>

html形式:

<form action="welcome.php" method="post"> 
<label>My favorite color:
    <input type="text" name="favorite_color">
</label>
<input type="submit" value="Save">
</form>

和插入数据的php代码:

<?php
$link = mysqli_connect("localhost", "root", "", "my_db");
 
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
$sql = "INSERT INTO colors (id, favorite_color, user_id) VALUES (?, ?, ?)";
 
if($stmt = mysqli_prepare($link, $sql)){
    mysqli_stmt_bind_param($stmt, "sss", $id, $favorite_color, $user_id);
    
    $id = $_REQUEST['id'];
    $favorite_color = $_REQUEST['favorite_color'];
    $user_id = $_REQUEST['user_id'];

    if(mysqli_stmt_execute($stmt)){
        echo "Records inserted successfully.";
    } else{
        echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
    }
} else{
    echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
 
mysqli_stmt_close($stmt);
 
mysqli_close($link);
?>

我做错了什么?欢迎任何建议。谢谢。

我已经解决了问题。

这是我所做的:

我改了:

$sql = "INSERT INTO colors (id, favorite_color, user_id) VALUES (?, ?, ?)";
 
if($stmt = mysqli_prepare($link, $sql)){
    mysqli_stmt_bind_param($stmt, "sss", $id, $favorite_color, $user_id);

进入:

$sql = "INSERT INTO colors (favorite_color, user_id) VALUES (?, ?)";
 
if($stmt = mysqli_prepare($link, $sql)){
    mysqli_stmt_bind_param($stmt, "si", $favorite_color, $user_id);

如您所见,我删除了 'id' 并将“sss”更改为“si”。

然后我改变了:

$id = $_REQUEST['id'];
$favorite_color = $_REQUEST['favorite_color'];
$user_id = $_REQUEST['user_id'];

进入:

$favorite_color = $_REQUEST['favorite_color'];
$user_id = $_SESSION['user_id'];

我完全删除了 'id',并将列 'user_id' 的 REQUEST 替换为 SESSION。

它现在以 table 种颜色显示 'user_id' 下方的匹配号码。