Insert ID of a Table in another Table [duplicate]

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);
?>
    
asked by anonymous 02.09.2017 / 21:26

2 answers

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 do an INSERT on "table2" by taking the Id_titulo field of "table1" whose id is 9999, throwing the data in the second field (assuming the first one is a primary key).

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

    
02.09.2017 / 22:16
2

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

Only 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 features like cascade, etc., you can create a foreign key. But in MySQL this feature is only available for the InnoDB engine.

To read more about Foreign Key: link

    
02.09.2017 / 21:39