Loop to database insertion

0

I want to upload each one of the: Titles, Lists and descriptions Knowing that: $ title is executed 40 times with different titles $ list is executed 40 times with different list $ description is executed 40 times with different description I can not get the (3) elements uploaded to the database at the same time when going through the foreach. I must say that I deleted code here because I have more code and more data, I wanted to make it as simple as possible. There is some way to do it, if something is wrong I will edit my question, thank you very much

CONNECTION TO THE BD

$usuario = "root";
$password = "";
$servidor = "localhost";
$basededatos = "lista_o";
$conexion = mysqli_connect( $servidor, $usuario, $password ) or die ("No se ha podido conectar al servidor de Base de datos");
$db = mysqli_select_db( $conexion, $basededatos ) or die ( "Upps! Pues va a ser que no se ha podido conectar a la base de datos" );

The data of these foreachs are from another website

foreach($match[1] as $urls)
{
      foreach($buscamea[1] as $tengoas)
      {
          foreach($titulos[1] as $titulo)
            {
              //AQUI MUESTRAN TODOS LOS TITULOS
              echo "<p>".$titulo."</p>";
            }
          foreach($listas[1] as $lista)
            {
              echo $lista;
            }
          foreach($descripciones[1] as $descripcion)
          {
            echo "<p>".$descripcion."</p>";
          }
      }
}
$insertar = mysqli_query($conexion, "INSERT INTO backup (nombre, desc_corta, desc_larga) VALUES
('$titulo', '$lista', '$descripcion')");
   if (!$insertar) {
 die("Fallo al guardar los datos:" . mysqli_error($conexion));
}
else {
 echo "<center><h1>subido con exito</h1></center>";
}
 mysqli_close( $conexion );

ASD

    
asked by Marco Torres 18.07.2018 в 03:00
source

1 answer

0

Without really understanding what you want to do and looking at the code, maybe in this case the easiest thing would be to use a single for foreach instead of that foreach cluster, on the other hand if you execute the query later The foreach is only saving the last values of the loops.

Example with for:

$sql = "INSERT INTO backup (nombre, desc_corta, desc_larga) VALUES (?, ?, ?)";
if ($stmt = mysqli_prepare($conexion , $sql)) {

    $count = count($titulos[1]);
    for($i=0; $i<$count; $i++) {
        /* ligar parámetros para marcadores */
        mysqli_stmt_bind_param($stmt, "sss", $titulos[1][$i], $listas[1][$i], $descripciones[1][$i]);

        /* ejecutar la consulta */
        mysqli_stmt_execute($stmt);

        /* Mostrar */
        echo "<p>".$titulos[1][$i]."</p>";
        echo "<p>".$listas[1][$i]."</p>";
        echo "<p>".$descripciones[1][$i]."</p>";
    }
}
    
answered by 18.07.2018 / 03:29
source