Error when validating an INSERT INTO of a foreach

0

guys I have the following code:

My code

     <?php
 $lote = $_REQUEST['lote'];
        $lote_pedido = str_replace("    ", " ", $lote);
        $datos = $lote_pedido;
    // divides por espacios y cada 6 elementos, los elementos de cada fila
    $temp = array_chunk(explode(' ', $datos), 6);
    $ar = array();


    foreach($temp as $key => $v) {
        // optienes el 1º elemento monto
        $ar[$key]['monto'] = array_shift($v);
        // optienes el ultimo elemento, serial
        $ar[$key]['serial'] = array_pop($v);
        // lo que queda es el codigo, lo unes con espacios
        $ar[$key]['codigo'] = implode(' ', $v);

        $monto =   $ar[$key]['monto'];
        $codigo =  $ar[$key]['codigo'];
        $serial =  $ar[$key]['serial'];

        $sql = "INSERT INTO tarjetas (id, monto, codigo, serial, usuario, id_pedido)
            VALUES(null, '$monto', ' $codigo', '$serial', '$user', '$id_pedido')"; 
           $resultado_ingreso = mysqli_query($db, $sql) or $error= (mysqli_error($db));


    }

    if (!$resultado_ingreso){
      $_SESSION['msn_pedidos_entrega']  = "Algo ha Ocurrido<br>" . $error;
    } else { // Aqui se ejecutan una serie de Update e Insert en otras tablas

What I have and what I do

The serial field of the table cards in my database has a UNIQUE key. I am trying if any of the data I am entering for any reason is repeated with any of the data stored in the database, then it is not effect the INSERT of the data that I am entering.

As it is, if for some reason I am entering the following data:

1 1111 1111 1111 1111 1111111111111
2 2222 2222 2222 2222 2222222222222

And the data already exists in the database

1 1111 1111 1111 1111 1111111111111

The system tells me the error that the following error exists:

  

Duplicate entry '1111111111111' for key 'serial'

But it is done in INSERT of the second data and I would like you not to do the INSERT but to identify which of the data is the one that is repeated.

    
asked by Jose M Herrera V 26.09.2018 в 00:16
source

1 answer

0

Use Transactions. Before the foreach, you initiate the transaction, and commit it, at the end of the cycle. Normally they are used together with try / catch blocks (exceptions), so that in the CATCH you can call rollback and exit the cycle.

Documentation of transactions

Documentation of exceptions

    
answered by 26.09.2018 в 00:29