I'm doing a project where I want to insert a record into two tables, where the user table has a primary key , and I have a client table > where there is a foreign key related to the primary key of the first one.
What I have tried to do is use two try catch , one to create the records for the user table, retrieve the id from the last record of the same, and insert the record of the customer table with the last record of user . The problem is that when I execute my code the second record in the second table. How can I do them: Here's the php code.
try {
if ($conSQL) {
$conSQL->beginTransaction();
$sqlStatment = $conSQL->prepare(
"INSERT INTO usuario VALUES(
default,
:usuario,
:tipo,
:nombre,
:app,
:apm,
:contrasena)");
$sqlStatment->bindParam(':usuario', $usuario);
$sqlStatment->bindParam(':tipo', $tipo);
$sqlStatment->bindParam(':nombre', $nombre);
$sqlStatment->bindParam(':app', $app);
$sqlStatment->bindParam(':apm', $apm);
$sqlStatment->bindParam(':contrasena', $contrasena);
//linea agregada
$sqlStatment->execute();
$lastInsertId = $conSQL->lastInsertId();
$conSQL->commit();
try {
if ($conSQL) {
$conSQL->beginTransaction();
$sqlStatment = $conSQL->prepare(
"INSERT INTO cliente VALUES(
default,
:idu,
:rfc,
:empresa,
:telefono,
:domicilio,
:contacto)");
$sqlStatment->bindParam(':idu', $lastInsertId);
$sqlStatment->bindParam(':rfc', $rfc);
$sqlStatment->bindParam(':empresa', $empresa);
$sqlStatment->bindParam(':telefono', $telefono);
$sqlStatment->bindParam(':domicilio', $domicilio);
$sqlStatment->bindParam(':contacto', $contacto);
//linea agregada
$sqlStatment->execute();
$conSQL->commit();
}
} catch (PDOException $e) {
$conSQL->rollBack();
}
}
} catch (PDOException $e) {
$conSQL->rollBack();
}
I thank you in advance for your great help. :)