How to ensure the Insert of all MYSQL data

Asked

Viewed 63 times

-3

I need to ensure that ALL data is entered, otherwise carry out a reversal and those that are entered are removed.

I have the following case

$dia1_entrada = $_POST['dia1_entrada'];
$dia1_pausa_almoco = $_POST['dia1_pausa_almoco'];
$dia1_inicio_tarde = $_POST['dia1_inicio_tarde'];
$dia1_saida = $_POST['dia1_saida'];
$dia1_carga = $_POST['dia1_carga'];
$data[]=array("fk_id_jornada_trabalho"=>$resultado,"dia"=>1,"entrada"=>$dia1_entrada,"inicio_pausa"=>$dia1_pausa_almoco,"fim_pausa"=>$dia1_inicio_tarde,"saida"=>$dia1_saida,"duracao_em_horas"=>$dia1_carga,"fk_id_administrador"=>ADM_ID);

$dia2_entrada = $_POST['dia2_entrada'];
$dia2_pausa_almoco = $_POST['dia2_pausa_almoco'];
$dia2_inicio_tarde = $_POST['dia2_inicio_tarde'];
$dia2_saida = $_POST['dia2_saida'];
$dia2_carga = $_POST['dia2_carga'];
$data[]=array("fk_id_jornada_trabalho"=>$resultado,"dia"=>2,"entrada"=>$dia2_entrada,"inicio_pausa"=>$dia2_pausa_almoco,"fim_pausa"=>$dia2_inicio_tarde,"saida"=>$dia2_saida,"duracao_em_horas"=>$dia2_carga,"fk_id_administrador"=>ADM_ID);

the insertion is made as follows

foreach($data as $item)
   $jornadaDao->insert($item);

However, if for some reason there is a connection failure or other reason for not inserting a line, for example, I should return an error and not insert any. But the way it is, if this happens, it will insert some and not others. Is there any way to make Insert only validated if everyone has entered, and if not, not to enter any? The solution can be made in PHP, or SQL itself...

1 answer

3

You can use Transaction, this ensures that all transactions are carried out, if any error nothing will be committed or inserted follows example.

try{
  $db->beginTransaction();
// sua regra INSERT - DELETE - UPDATE
$db->commit();
}catch() {
  $db->rollBack()
}

Very simple example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.