Utilize Prepared statements to avoid SQL Injection. Your question is a good example of how to use transactions and exceptions.
If the first Insert work, will be written to the database. In case the second fails, the message Gravado com sucesso
will be displayed, in addition to causing confusion, the database will be with an inconsistent result.
Use transactions to inform the bank that all SQL statements must be performed successfully to write to the bank, in case one fails the others will be undone (rollback
).
By turning mistakes into exceptions with mysqli_report any failure in mysqli_prepare or mysqli_stmt_execute the block catch
will run, in which case will only display the error message, but other treatments can be done.
Case the two of you Inserts are successfully executed, mysqli_commit, will put the changes into effect or save the new records.
<?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? How? Why?
What is a Mysql Transaction for?
It stops showing error when I write any value in the database, it is as if the
$nome = $_POST['nome'];
when I open it’s empty, so much so that it records in the empty bank– WSS
Updates the form of your question.
– rray