Write data in two tables from a PHP form

1

Connection to bd

$host = "localhost";

$user = "root";

$pass = "";

$conexao = mysqli_connect($host, $user, $pass) or die (mysql_error());

mysqli_select_db($conexao, "teste2");

HTML

<head>  
    <title>Gravar</title>
</head>
<body>
    <form type="text" method="post">
        <input type="text" name="nome">
        <input type="submit" value="enviar">
</body>

PHP

$nome = $_POST['nome'];

$sql = mysqli_query($conexao,"INSERT INTO teste1 (nome) values ('$nome')");

$sql2 = mysqli_query($conexao, "INSERT INTO teste2 (nome) values ('$nome')");

echo 'Gravado com sucesso';

Why can not I write the (name) table in test1 and test2?

Note: db calls test2 even

    
asked by anonymous 30.09.2015 / 15:42

2 answers

5

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?

    
30.09.2015 / 17:36
0

Place: name="submit", in the submit button.

And replace the php code from the bottom.

if( 'POST' == $_SERVER['REQUEST_METHOD'] && $_POST['submit'] == 'enviar' ){

    $nome = $_POST['nome'];

    $sql = mysqli_query($conexao,"INSERT INTO teste1 (nome) values ('$nome')");

    $sql2 = mysqli_query($conexao, "INSERT INTO teste2 (nome) values ('$nome')");

    echo 'Gravado com sucesso';

}
    
30.09.2015 / 16:44