'How to let logged in user insert data into database

Situation: user is logged in and wants to save their favorite color through html form.

Page where logged in user is after logging in: welcome.php.

welcome.php starts with:

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

The html form in welcome.php:

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

The php code below the form:

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

There are two tables in phpMyAdmin:

users

colors

FYI, I have created a FOREIGN KEY constraint on the "user_id" column in table colors.

When user saves their color, they will see the following error:

ERROR: Could not execute query: INSERT INTO colors (favorite_color) VALUES (?).

What am I doing wrong? Thanks a bunch for any suggestion!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source