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!';
}
}
}
?>