how to insert data in php array, mysqli?

1

I need to insert multiple records in a mysql table, from another table, but only the first record in the table is inserted my code is as follows

if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
}
echo "Conectado a la base de datos correctamente";
//Obtener checadas desde el biometrico
$asistencia = $zk->getAttendance();
foreach($asistencia as $key=>$valor) {
  $id = $valor[1];
  foreach ($conn->query("SELECT * FROM usuariosBiometrico WHERE id=".$id) as $dato) {
    $chofer = $dato['usuario'];
  }
  $fecha = date( "Y-m-d", strtotime( $valor[3] ) );
  $hora = date( "H:i:s", strtotime( $valor[3] ) );
  $datosInsertar = array(
    'chofer' => $chofer,
    'fecha' => $fecha,
    'hora' => $hora
  );
  echo json_encode($datosInsertar);
  $sql = "INSERT INTO checadas (chofer, fecha, hora) VALUES ('".implode("', '", $datosInsertar)."')";
}

if (mysqli_query($conn, $sql)) {
      echo "Registros insertados correctamente";
} else {
      echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);

in the JSON if all records are shown but when you insert them into the database, only one record is inserted What can I do to insert all the records in the corresponding fields?

    
asked by Saul Espinoza 11.06.2018 в 22:39
source

1 answer

1

The problem is that you are doing the incersion out of the loop. You have to do it after each iteration like this:

if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
}
echo "Conectado a la base de datos correctamente";
//Obtener checadas desde el biometrico
$asistencia = $zk->getAttendance();
foreach($asistencia as $key=>$valor) {
  $id = $valor[1];
  foreach ($conn->query("SELECT * FROM usuariosBiometrico WHERE id=".$id) as $dato) {
    $chofer = $dato['usuario'];
  }
  $fecha = date( "Y-m-d", strtotime( $valor[3] ) );
  $hora = date( "H:i:s", strtotime( $valor[3] ) );
  $datosInsertar = array(
    'chofer' => $chofer,
    'fecha' => $fecha,
    'hora' => $hora
  );
  echo json_encode($datosInsertar);
  $sql = "INSERT INTO checadas (chofer, fecha, hora) VALUES ('".implode("', '", $datosInsertar)."')";
  if (mysqli_query($conn, $sql)) {
      echo "Registros insertados correctamente";
  } else {
      echo "Error: " . $sql . "<br>" . mysqli_error($conn);
  }
}

mysqli_close($conn);
    
answered by 11.06.2018 / 22:46
source