Upload CSV to database using php

I’m working on a small project of mine, and I came to the conclusion that the ability to automatically load an excel sheet into my database will be very, very useful, the problem is that I don’t know where I first researched a bit and decided to use a CSV file, created from excel sheet to load data into the table of my database.

Most of the examples I came across look like a mess with the PHP code in html, instead of sharing the logic in different files, like what I have done over the past 2 months.

Now I have a upload form in html:

       <form enctype="multipart/form-data" method="post" id="uploadForm">
          <input name="filesfiles" id="upload" type="file" accept=".csv" class="left" />
          <input type="submit" value="Cargar" />
       </form>

And a small example of how the CSV file looks in the text:

Cedula;Nombre;Apellido1;Apellido2;Correo;IdRol;Estado
1657890;Dominico;Scarlatti;Viera;leetrills@yahoo.com;2;0
5657890;Franz;Listz;Linerman;flizts@hotmail.com;3;0

Or in some other versions of excel:

Cedula,Nombre,Primer Apellido,Segundo Apellido,Correo,IDRol,Estado
126548791,Franz ,Ritter ,von Liszt,fliszt@arppegio.com,3,0
174657109,Sofia ,Asgatovna ,Gubaidulina ,gubaidulina@yahoo.com,3,0

The first row is the name of the columns (which should be ignored when adding information) to the table into which I want to upload the file.

, , PHP- , CSV .

EDIT:

JSFiddle

EDIT4:

- . . , , - - .

<?php

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING & ~E_STRICT);

mysql_connect('localhost', 'root', '');
mysql_select_db("proyecto") or die(mysql_error());

if (isset($_FILES['csvupload'])) {
    $errors = array();
    $allowed_ext = array('.csv');

    $file_name = $_FILES['csvupload']['name'];
    $file_ext = strtolower(end(explode('.', $file_name)));
    $file_size = $_FILES['csvupload']['size'];
    $file_tmp = $_FILES['csvupload']['tmp_name'];

    if (in_array($allowed_ext) === false) {
        $errors[] = 'La extensión del archivo no es valida.';
    }
    if ($file_size > 10485760) {
        $errors[] = 'El archivo sobrepasa el limite de 10MB';
    }
    if (empty($errors)) {

        $handle = fopen($file_tmp, "r");

        while (!feof($handle)) {
    $value = (fgetcsv($handle, 0, ','));
    if ($i > 0) {
        if ($value[0] != '') {
            $inserts[] = "('" . mysql_real_escape_string($value[0]) . "','"
                    . mysql_real_escape_string($value["1"]) . "','"
                    . mysql_real_escape_string($value["2"]) . "','"
                    . mysql_real_escape_string($value["3"]) . "','"
                    . mysql_real_escape_string($value["4"]) . "','"
                    . mysql_real_escape_string($value["5"]) . "','"
                    . mysql_real_escape_string($value["6"]) . "')";
        }
    } elseif ($i == 0) {
        $fields = $value;
    }
    $i++;
}

mysql_query("INSERT INTO `usuarios` (`cedula`,`nombre`,`apellido1`,`apellido2`,`correo`,`idRol`,`estado`) VALUES " . implode(",", $inserts));
        fclose($handle);
        if ($sq1) {
            echo '¡Los usuarios han sido agregados exitosamente!';
        }
    }
}
?>
+4
2

, ,

$file = fopen($_FILES['csvUpload']['tmp_name'], "r");
$i = 0;
while (!feof($file)) {
    $value = (fgetcsv($file, 0, ';'));
    if ($i > 0) {
        if ($value[0] != '') {
            $inserts[] = "(" . $value[0] . ","
                    . $value["1"] . ","
                    . $value["2"] . ","
                    . $value["3"] . ","
                    . $value["4"] . ","
                    . $value["5"] . ","
                    . $value["6"] . ")";
        }
    } elseif ($i == 0) {
        $fields = $value;
    }
    $i++;
}

mysql_query("INSERT INTO `MyTable` (`" . $fields[0] . "`,`" . $fields[1] . "`,`" . $fields[2] . "`,`" . $fields[3] . "`,`" . $fields[4] . "`,`" . $fields[5] . "`) VALUES " . implode(",", $inserts));

fclose($file);

, . . MySQL . , !

1:

, , .

<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING);

mysql_connect('localhost', 'root', '');
mysql_select_db("proyecto") or die(mysql_error());

if (isset($_FILES['csvUpload'])) {
    $errors = array();
    $allowed_ext = array('.csv');

    $file_name = $_FILES['csvUpload']['name'];
    $file_ext = strtolower(end(explode('.', $file_name)));
    $file_size = $_FILES['csvUpload']['size'];
    $file_tmp = $_FILES['csvUpload']['tmp_name'];

    if (in_array($allowed_ext) === false) {
        $errors[] = 'La extensión del archivo no es valida.';
    }
    if ($file_size > 10485760) {
        $errors[] = 'El archivo sobrepasa el limite de 10MB';
    }
    if (empty($errors)) {


        $handle = fopen($file_tmp, "r");
        while (($fileop = fgetcsv($handle, ";") && fgetcsv($handle, ",")) !== false) {
            $cedula = mysql_real_escape_string($fileop[0]);
            $nombre = mysql_real_escape_string($fileop[2]);
            $apellido1 = mysql_real_escape_string($fileop[3]);
            $apellido2 = mysql_real_escape_string($fileop[4]);
            $correo = mysql_real_escape_string($fileop[5]);
            $idRol = mysql_real_escape_string($fileop[6]);
            $estado = mysql_real_escape_string($fileop[9]);


            $sq1 = mysql_query("INSERT INTO `usuarios` (cedula,nombre,apellido1,apellido2,correo,idRol,estado) VALUES ('$cedula','$nombre','$apellido1','$apellido2','$correo','$idRol','$estado')");
        }
        fclose($handle);
        if ($sq1) {
            echo '¡Los usuarios han sido agregados exitosamente!';
        }
    }
}
?>



<form enctype="multipart/form-data" method="post" id="uploadForm">
    <input name="csvUpload" id="upload" type="file" accept=".csv" class="left" />
    <input type="submit" value="¡Cargar!" />
</form>
+2

    <form enctype="multipart/form-data" action="uploader.php" method="POST">
    <ul><li>
     <input name="file" type="file" /><br /></li><li>
    <br><input type="submit" name="submit" value="Upload" /></li>
    </ul>
    </form>

uploader.php

            <?php
    if (isset($_FILES['file'])) {
    $errors = array();
    $allowed_ext = array('csv');

    $file_name = $_FILES['file']['name'];
    $file_ext = strtolower(end(explode('.', $file_name)));
    $file_size = $_FILES['file']['size'];
    $file_tmp = $_FILES['file']['tmp_name'];

    if (in_array($file_ext, $allowed_ext) === false) {
        $errors[] ='Extension not allowed';
    }
    if ($file_size > 10485760) {
       $errors[] = 'File size must be under 10mb';
    }
    if (empty($errors)) {





        $handle = fopen($file_tmp,"r");
        while(($fileop = fgetcsv($handle,",")) !== false) 
        {
        $companycode =  mysql_real_escape_string($fileop[0]);
        $pdtcode = mysql_real_escape_string($fileop[2]);
        $Item = mysql_real_escape_string($fileop[3]);
        $pack = preg_replace('/[^A-Za-z0-9\. -]/', '', $fileop[4]);
        $lastmonth = mysql_real_escape_string($fileop[5]);
        $ltlmonth = mysql_real_escape_string($fileop[6]);
        $op = mysql_real_escape_string($fileop[9]);
        $pur = mysql_real_escape_string($fileop[10]);
        $sale = mysql_real_escape_string($fileop[12]);
        $bal = mysql_real_escape_string($fileop[17]);
        $bval = mysql_real_escape_string($fileop[18]);
        $sval = mysql_real_escape_string($fileop[19]);

        $sq1 = mysql_query("INSERT INTO `sas` (companycode,pdtcode,Item,pack,lastmonth,ltlmonth,op,pur,sale,bal,bval,sval) VALUES ('$companycode','$pdtcode','$Item','$pack','$lastmonth','$ltlmonth','$op','$pur','$sale','$bal','$bval','$sval')");
    }
    fclose($handle);
    if($sq1){
        echo 'Stock and Sales successfully updated. Please check the values.<br><br>'; 



            }
        } 
    ?>

. .

0

Source: https://habr.com/ru/post/1537931/


All Articles