Use prepared statements to avoid SQL injection. Your question is a good example of how to use transactions and exceptions .
If the first insert works, it will be written to the database. If the second fails, the Gravado com sucesso
message will appear, in addition to causing confusion, the database will have an inconsistent result.
Use transactions to inform the bank that all SQL statements must be successfully written to the database, if one fails the others will be undone ( rollback
).
Turning errors into exceptions with mysqli_report any faults in mysqli_prepare or mysqli_stmt_execute the catch
block will run, in which case it will only display the error message, but other treatments can be done.
If both inserts run successfully, mysqli_commit , go make changes, or record new registrations.
<?php
$conexao = mysqli_connect($host, $user, $pass);
mysqli_autocommit($conexao, false);
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
$nome = 'teste';
$insert1 = false;
$insert2 = false;
try{
$stmt = mysqli_prepare($conexao, "INSERT INTO teste1 values (?)");
mysqli_stmt_bind_param($stmt, 's', $nome);
$insert1 = mysqli_stmt_execute($stmt);
$stmt = mysqli_prepare($conexao, "INSERT INTO teste2 (nome) values (?)");
mysqli_stmt_bind_param($stmt, 's', $nome);
$insert2 = mysqli_stmt_execute($stmt);
}catch (mysqli_sql_exception $e){
echo 'SQLState: '. $e->getCode() .' <br>Descrição: '. $e->getMessage();
}
if($insert1 && $insert2){
mysqli_commit($conexao);
echo 'sucesso';
}
mysqli_close($conexao);
Recommended reading:
MySQL Transaction When? As? Why?
What is a MySQL Transaction for?