I have the following code:
<?php
function entregar_pedido(){
global $db;
$id_pedido = ($_GET['id']);
$user = ($_GET['user']);
//$lote = $_REQUEST['lote'];
$lote = "1 1111 1111 1111 1111 1111111111111111 2 2222 2222 2222 2222 222222222222222"
$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')";
mysqli_query($db, $sql);
$resultado_ingreso = mysqli_query($db, $sql) or mysqli_error($db);
}
if (mysqli_query($db, $sql) === TRUE) {
$_SESSION['msn_pedidos_entrega'] = "Se ha entregado el Pedido con Exito.<br>";
} else {
$_SESSION['msn_pedidos_entrega'] = "Algo ha Ocurrido.<br>";
$_SESSION['msn_pedidos_entrega'] .= "Error: " . $sql . "<br>" . $db->error;
}
?>
I can not understand why the script performs the INSERT in a duplicated way in the database, I have temporarily configured in the database the structure of the serial column to work as a single key and not be stored duplicate data but I also get the error:
Error: INSERT INTO tarjetas (id, monto, codigo, serial, usuario, id_pedido) VALUES(null, '123456788', ' ', '', 'prueba', '37')
Duplicate entry '' for key 'serial'
The issue is that there is a possibility in the future that the same serial belongs to another code or that the same code has different serial numbers, so it is required that the entry to the database is not done as it is doing in this moment.