Help with If statement during data entry in MySQL in PHP

1

I need help with the following sentence

$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 {

The statement as it gets the data to insert in the table cards of a foreach , in a single run you can add for example 10 new rows to my database, but if 1 of those 10 rows is not admitted by my database by previous configuration of UNIQUE keys, an error can occur with that single row but not with the remaining 9 rows and I would like the sentence to be so 9 of the 10 data are added as 1 error was generated then it remains in the message that something has happened and does not continue executing the script since after the else there is a series of UPDATE and mailings to the user notifying of the assignment.

Here is my Complete Function

function entregar_pedido(){
  global $db;

  $id_pedido = ($_GET['id']);
  $user = ($_GET['user']);


  $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 {

$status = 'ENTREGADO';
$admin = $_SESSION['user']['username'];
$concepto = "ASIGNACION DE TARJETAS";

$sqlUPDATE = "UPDATE pedidos SET
status_pedido = '$status'
WHERE id = '$id_pedido'";

if (mysqli_query($db, $sqlUPDATE)) {
$_SESSION['msn_pedidos_entrega']  = "Se ha Actualizado el STATUS del pedido..!!<br>";
} else {
echo "Error updating record: " . mysqli_error($db);
//mysqli_close($db);
}


$query = "INSERT INTO bitacora (
id,
id_pedido,
status,
admin,
concepto) 
VALUES(null, '$id_pedido', '$status', '$admin', '$concepto')";
  //mysqli_query($db, $query);
    $resultado_ingreso = mysqli_query($db, $query) or mysqli_error($db);


if (count($ar)<2){
$t= "Tarjeta";
} else {
$t= "Tarjetas";
}
$_SESSION['msn_pedidos_entrega']  .= "Se ha entregado el Pedido con Exito.<br>";
$_SESSION['msn_pedidos_entrega']  .= "En esta Transaccion fueron asignadas " .count($ar)." ".$t." <br>";

$sql1="SELECT sum(monto) AS 'total'
  FROM tarjetas
  WHERE usuario = '$user' AND id_pedido = '$id_pedido'";
  $result1 = mysqli_query($db, $sql1);

  while ($row1 = mysqli_fetch_assoc($result1)) 
{
  if ($row1['total']<1){
    echo "No se Ha encontrado Tarjetas Asignadas a este Usuario";
      } else {
        $_SESSION['msn_pedidos_entrega']  .= "Total de BsS Entregado ".$row1['total']." BsS<br>";
}
}

$sql2 = "SELECT tarjetas.*, users.nombre, users.email, users.username FROM tarjetas INNER JOIN users  ON tarjetas.usuario=users.idusuario WHERE usuario = '$user' AND id_pedido = '$id_pedido' ";
$result2 = mysqli_query($db, $sql2);
//if (mysqli_query($db, $query)){
$row2count =  mysqli_num_rows($result2);
//$row2 =  mysqli_fetch_assoc($result2);

  $tarjetas = '<table class="table table-bordered table-hover ">';
  $tarjetas .= '<thead><tr>';
  $tarjetas .= '<th height="17" width ="20%" align="center">';
  $tarjetas .= 'MONTO';
  $tarjetas .= '</th>';
  $tarjetas .= '<th height="17" width ="20%" align="center">';
  $tarjetas .= 'CODIGO';
  $tarjetas .= '</th>';
  $tarjetas .= '<th height="17" width ="20%" align="center">';
  $tarjetas .= 'SERIAL';
  $tarjetas .= '</th>';
  $tarjetas .= '</tr></thead>';

while ($row2 = mysqli_fetch_assoc($result2)) {
  $monto = $row2['monto'];
  $codigo = $row2['codigo'];
  $serial = $row2['serial'];
  $email_usuario = $row2['email'];
  $nombre_usuario = $row2['nombre'];

  $tarjetas .= '<tr>';

  $tarjetas .= '<td align="center">';
  $tarjetas .= $monto;
  $tarjetas .= '</td>';
  $tarjetas .= '<td align="center">';
  $tarjetas .= $codigo;
  $tarjetas .= '</td>';
  $tarjetas .= '<td align="center">';
  $tarjetas .= $serial;
  $tarjetas .= '</td>';
  $tarjetas .= '</tr>';
}
  $tarjetas .=  '</table>';

  $tarjetas_asignadas = $tarjetas;


$_SESSION['msn_pedidos_entrega']  .= "En total se le han asignado ".$row2count." tarjetas al usuario " .$user."<br>";

$email = $email_usuario;
$nombre = $nombre_usuario;
$asunto = "ASUNTO";
$cuerpo = "CUERPO DEL MENSAJE";

enviarEmail($email, $nombre, $asunto, $cuerpo);

$_SESSION['msn_pedidos_entrega']  .= '<i class="fa fa-envelope"></i> Se ha enviado un correo electronico notificando sobre esta asignacion de pedido..!!<br>';

}
}
    
asked by Jose M Herrera V 06.11.2018 в 16:43
source

1 answer

1

You can use try and catch to continue the execution of the loop like this:

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'];
  try {
      $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));
  } catch (Exception $e) {
      // Aqui puedes desplegar el error si quieres
      continue;
  }

}
    
answered by 06.11.2018 / 17:06
source