php - How to insert the User ID to the table when the user is logged in
I got MySQL Database with the tables users and pictures. Then I created a upload.php page where my logged in user can upload the pictures, that are later stored (id, name, path and user_fk) to the database. However, it shows me the error. Name and image input worked well but after I tried to insert users id, id didn't work well.
The error says :
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
pictures
, CONSTRAINTpictures_ibfk_1
FOREIGN KEY (user_fk
) REFERENCESusers
(user_id
)) in /Applications/MAMP/htdocs/pinterest/upload.php:23 Stack trace: #0 /Applications/MAMP/htdocs/pinterest/upload.php(23): PDOStatement->execute() #1 {main}Success
<?php
session_start();
require_once __DIR__.'/connect.php';
require_once 'top.php';
$sUserId = $_SESSION['txtUsername'];
?>
<div class="bigTitle"><h2>Welcome <?php echo $sUserId ?> here you can upload your pictures.</h2></div>
<?php
require_once __DIR__.'/connect.php';
if(isset($_POST['submit']))
{
$sName = $_POST['name'];
$img = $_FILES['image']['name'];
$sUserId = $_SESSION['txtUsername'];
try{
$stmt = $db->prepare('INSERT INTO pictures VALUES (null, :sName, :sImage, :sUserId)');
$stmt->bindValue(':sName', $sName);
$stmt->bindValue(':sImage', $img);
$stmt->bindValue(':sUserId', $sUserId);
$stmt->execute();
}catch (PDOEXception $ex){
echo $ex;
}
move_uploaded_file($_FILES['image']['tmp_name'], "images/$img");
echo 'Success';
}
?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="text" name="name" placeholder="name">
<input type="file" name="image" placeholder="image upload">
<input type="submit" name="submit" value="Upload the picture">
</form>
?>
I'm curious if there is any problem with the session or with the tables in database.