How to insert the PK value of one table in the FK of another table

0

I created a usuario table using:

CREATE TABLE usuario(
    usuario_id int NOT NULL auto_increment PRIMARY KEY,
    nome varchar(200));

Then another table using:

CREATE TABLE image(
    id int NOT NULL auto_increment PRIMARY KEY,
    nome varchar(200) NOT NULL,
    id_user int,
    FOREIGN KEY(id_user) REFERENCES usuario(usuario_id) ON CASCADE);

This is my framework for when a user uploads an image to the image table in addition to receiving a new id and the image address in the nome field, it also receives the id of the user that did the action. But nothing happens. The id_user field is null.

As far as I understand it is necessary that when I insert an image the field id_user receives the value of usuario_id automatically, I heard about the triggers but I can not implement this in the code.

Code that inserts into the image table:

<?php
include('conexao.php');

$uploaddir = 'uploads/';

if(empty($_FILES['arquivo']['name'])){
    header('Location: index.php');
    exit();
}


$uploadfile = $uploaddir.$_FILES['arquivo']['name'];


$sql = "INSERT INTO image(nome) VALUES('{$uploadfile}')";
if(mysqli_query($conexao, $sql)){
    if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $uploadfile)){
        header('Location: index.php');
        }
        else {
            echo "Falied to send!";
        }
    }
?>
    
asked by anonymous 11.11.2018 / 18:33

1 answer

0

There are several ways you can enter yourself, and you can enter it manually. If the user is logged in, in login authentication, if successful, he can declare a $_SESSION['id'] .

The insert would look like:

INSERT INTO image(nome, id_user) VALUES('{$uploadfile}', '$_SESSION[id]')
    
12.11.2018 / 06:09