How to enter the PK value of a table in the FK of another table

Asked

Viewed 131 times

0

I created a table usuario 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 a table image in addition to receiving a new id and the address of the image in the field nome, she also receive the id of the user who did the action. But nothing happens. The field id_user is void.

As far as I understand it is necessary that when inserting an image the field id_user receive the value of usuario_id automatically, I’ve heard of triggers but I’m not able to implement it in the code.

Code that makes the insertion in the table image:

<?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!";
        }
    }
?>
  • In the question you showed the structure of the two tables, but what was the code you wrote to make these record inserts? Without it there is no way to know what is wrong. And which database you are using?

  • I’ll ask the question.

  • If "heard of triggers", but does not know how to implement. There is no point in asking for help here because no one is going to do the code for you and teaching is something that here hardly helps. This community has a unique focus on helping solve problems through the exchange of information. Apparently your database is Mysql and there is an error in the syntax in the FOREIGN KEY statement for this content https://www.w3schools.com/sql/sql_foreignkey.asp

  • Read this article on triggers, it might help you understand the concept https://www.devmedia.com.br/mysql-triggers/8088

1 answer

0


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

The Insert would be:

INSERT INTO image(nome, id_user) VALUES('{$uploadfile}', '$_SESSION[id]')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.