1
Hello fellow developers,
I put together a script transaction to insert values into 2 different tables, or die at the end of each INSERT, so that the insertion of data does not occur in the second table, if an error occurs in the insertion of the first.
What has bothered me is that even if an error occurs in the insertion of the data and the process dies (not entering the data in the database), still table ID is reserved, making a successful next INSERT, the ID is not sequential compared to the previous record. NOTE: Both tables have auto_increment in ID.
Is there any way to solve this problem?
Below is an example of my code:
$mysqli->query('START TRANSACTION') or die($mysqli->error);
$sql = "INSERT endereco (logradouro, numero, complemento, bairro, cidade, uf) VALUES ('".$logradouro."','".$numero."','".$complemento."','".$bairro."','".$cidade."','".$uf."')";
$query = $mysqli->query($sql) or die($mysqli->error);
$idEndereco = $mysqli->insert_id;
$sql = "INSERT contato (email, telefone, telefone_adicional) VALUES ('".$email."','".$telefone."','".$telefoneAdicional."')";
$query = $mysqli->query($sql) or die($mysqli->error);
$idContato = $mysqli->insert_id;
$mysqli->query('COMMIT') or die($mysqli->error);
Thank you for the reply Inkeliz!
– Hugo Guitti