Insert data in several rows from a mysql php text file

0

What I'm trying to do is read a .txt file and save each of the rows and columns in their respective fields in MySQL. The problem is that it is not saved in the BD. So I have the text in the file:

NOMBRE,EDAD,SEXO
WALTHER,28,M
MARTHE,26,F
JULIO,28,M
MARIA,25,F
ESTEBAN,24,M

and so I have my code:

<html>
<head>
<title>Leer archivo</title>
</head>

<body>

<table>

<?php
    $f = fopen("archivo.txt", "r") or exit("no se puede leer archivo!");
    $arr_to_insert = array();
    while (!feof($f)) { 

       $arrM = explode(',',fgets($f)); 
       echo '<tr><td name="NOMBRE">' . $arrM[0] . '</td><td name="EDAD">' . $arrM[1] . '</td><td name="SEXO">' . $arrM[2] . '</td>  </tr>';

       $arr_to_insert[] = $arrM;
    }

    fclose($f);
if (isset($_POST['submit'])) {
include 'conexion.php';
foreach($arr_to_insert as $ai){
    $sql="INSERT INTO ninguno (NOMBRE, EDAD, SEXO) VALUES ('{$ai[0]}','{$ai[1]}','{$ai[2]}')";
    if (!mysqli_query($con,$sql))
      {
      die('Error: ' . mysqli_error());
      }

}
mysqli_close($con);
}
?>
</table>
</form>
</body>
</html>
    
asked by SeliGVyo 31.07.2017 в 04:55
source

2 answers

1

You can try this script.

Implement prepared queries. They are safer and more effective.

MySQLi is used in object-oriented style. I say this because you will see that the code varies slightly in the calls to MySQLi.

In your code I see that you were trying to create a table with the data at the same time. I did not do that, but it could be done if it's important to you.

I hope it serves you.

Comments in the code.

$path = 'ruta/y/nombre-archivo/csv.csv';

if(!file_exists($path))
{

    echo "!Archivo no existe!";     

}else{

    //Gestionar aquí conexión a la BD si es de lugar

    $sql="INSERT INTO ninguno (NOMBRE, EDAD, SEXO) VALUES (?, ?, ?)";
    $stmt = $mysqli->prepare($sql);

    $f = fopen($path, "r");

    //Contador para saltar primera línea. Necesario sólo si el csv incluye las cabeceras
    $linea = -1;

    while ($data = fgetcsv($f, 1000, ',', '"')) 
    { 

        $linea++;

        if($linea == 0)
        continue;

        if(current($data)) 
        {
            $nombre = $data[0];
            $edad = $data[1];
            $sexo = $data[2];
            $stmt->bind_param('sis', $nombre, $edad, $sexo);

            //Para fines de depuración
            echo "Insertando: ".$nombre." - ".$edad." - ".$sexo."\n";

            $stmt->execute();
        }

    }

    //Cerrar recursos
    fclose($f);

    $stmt->close();
    $mysqli->close();

}
    
answered by 31.07.2017 в 05:22
1

I will propose a solution using PDO , the code is commented directly, only saying that it is done use of PHP functions such as:

  • file_exists To check the existence of the file.
  • fopen To open the file in read mode Read (r)
  • fgets To read a file line.
  • explode To split a string using an (comma) delimiter , this method returns a array .

    <?php 
    $rutadefichero = "datos.txt";
    if(!file_exists ($rutadefichero)) echo "El archivo no Existe";
    else{
        $bd = new PDO('mysql:host=localhost;dbname=midatabase',"root", "miclave",array(PDO::ATTR_PERSISTENT => true));
        try { 
                /* Creamos La Conexión con PDO, modificar los valores respectivos*/
                $bd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                /* Creamos la Transacción*/
                $bd->beginTransaction();
                $sentencia = $bd->prepare("INSERT INTO person (nombre,edad,sexo) VALUES (:nombre,:edad,:sexo)");
                $recurso = fopen($rutadefichero, "r"); 
                //Lee La Primer Línea
                $contenidoleido = fgets($recurso); 
                //Lectura linea por línea  , verificando que no sea el final del archivo con feof
                while (!feof($recurso)) { 
                    /* Leemos la Línea */
                    $contenidoleido = fgets($recurso); 
                    /* Explode para separar la línea en un array usando como delimitador la coma */
                    $data = explode(",", $contenidoleido); 
                    $nombre = $data[0];
                    $edad = $data[1];
                    $sexo = $data[2];
                    $sentencia->bindValue(':nombre', $nombre, PDO::PARAM_STR);
                    $sentencia->bindValue(':edad', $edad , PDO::PARAM_INT);
                    $sentencia->bindValue(':sexo', $sexo, PDO::PARAM_STR);
                    $sentencia->execute();
                } 
                 /* Aplicamos los Cambios en La BD */
                $bd->commit();
            }
        catch (Exception $e) {
             /* Cancelamos La Transacción por si exista Error*/
            $bd->rollBack();
            echo "Se Presento Un Error :  " . $e->getMessage();
        }
    }
    ?>
    
answered by 31.07.2017 в 07:40