Insert data in 2 different tables

0

Good I need to insert data of a record of a user in 2 different ablas, the id in the table users is the primary key and in the table owners is the FK but when doing the query it does not record them register in the users table but not in the owners, I hope you can help me in the '' who are alone is because in the tables I have the autoincrementable id

<?php
session_start();
require_once('./../../conexion.php');
// recuperamos los datos del formulario
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$correo = ($_POST['correo']);
$clave =sha1(md5(123456));
$apartamento = $_POST['apartamento'];
$alicuota= $_POST['alicuota'];
$estado='Al dia';

// echo $nombre . "<br>";
// echo $apellido . "<br>";
// echo $correo . "<br>";
 // echo $clave . "<br>";
// echo $apartamento . "<br>";
// echo $alicuota ;


$consulta = "INSERT INTO usuarios VALUES('','$nombre','$apellido','$correo','$clave','$apartamento', '2',   
'$alicuota' )";

$query = mysqli_query($conexion, $consulta);





$consulta2 = "INSERT INTO propietarios VALUES('','$nombre','$apellido','$apartamento','$estado' )";

$query2 = mysqli_query($conexion, $consulta2);


if ($query2) {
	?>
	  <meta http-equiv="refresh" content="0;URL=./../index1.php"> 
	<?php
}
#header('Location: condominio.php');
?> 
    
asked by Anderson Rey 13.03.2018 в 04:59
source

1 answer

1

Hello! If you are generating the user ID with an auto_increment, then that ID does not yet exist in your code when you run the second insert, that of the owners.

In order to create the second record, you must obtain the ID generated in the database. This is achieved by executing another SQL query immediately after the first insert:

SELECT LAST_INSERT_ID();

With this query, you get the ID, which you can then use in the insert to the owners table. I assume that in this table, the empty string refers to the user ID, right? If that field is the user's FK, you should place the ID of the newly created user in the previous statement there. In fact, that's why you do not insert anything in the owners table, since you send an empty string where the ID associated with the FK should go, Mysql does not know who to associate the new record with, and therefore does not do anything . The same takes advantage of capturing the errors of Mysql, to always have the error codes at hand when you want to ask questions here or in google ^ _ ~

For more information, check the official documentation link of Mysql, for the LAST_INSERT_ID function: link

And to know the use of the mysqli class that you are using to connect from php: link

    
answered by 13.03.2018 / 13:04
source