Insert ID from one Table into another Table

Asked

Viewed 905 times

0

How do I insert the ID of a table into another table?

<?php
$login_cookie = $_COOKIE['login'];
    if (!isset($login_cookie)) {
      header("Location: index.php");
    }

$con = mysqli_connect('localhost', 'root', '', 'lista');
$paginas = $_POST["paginas"];
$ins = "INSERT INTO paginas (paginas, usuario) VALUES ('".$paginas."','".$login_cookie."')";


if(mysqli_query($con, $ins)) {

echo "Registrado com sucesso!";

} else {
    echo "Erro ao registrar!";
}

mysqli_close($con);
?>
  • You want to get the ID after the INSERT, right? This should resolve https://answall.com/questions/89986/pega-o-id-da-last-entered lintel no-data

2 answers

2

Just create a column in the other table with exactly the same data type, e.g., if you have the column in the first table being INT(11) UNSIGNED, in the other table you need to be exactly INT(11) UNSIGED.

Just by doing this, you already have the logic to work with this data, but if you want to create the relationship physically to use other resources like cascade, etc., you can create a foreign key (Foreign Key). However in Mysql this feature is only available for the Innodb engine.

To read more about Foreign Key: https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html

  • I still have not understood mt well how to put in practice. In case I’m starting agr to study. I am creating a system that stores total read book pages. The user goes to the title profile and will have an input for him to type the page that stopped. There are 3 tables, a pro user, title and pages, I managed to enter the user with cookie and pages. But I’m not sure how to pull the title id to save on the table.

2


You can do a SELECT and INSERT in the same query:

INSERT INTO tabela2
SELECT
null,
Id_titulo
FROM tabela1
WHERE Id = '9999'

The above code will make an INSERT in the "table2" taking the field Id_titulo of "Tabela1" whose Id is 9999, throwing the die into the second field (assuming that the first is a primary key).

The code is just one example. You need to adapt it to the structure of your tables.

  • Please avoid long discussions in the comments; your talk was moved to the chat

Browser other questions tagged

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