我正在研究我的一个小项目,我得出结论,能够自动将excel表格上传到我的数据库将是非常非常有用的,问题是我不知道从哪里开始,我研究了一下,并决定使用从Excel工作表创建的CSV文件将数据上传到我的数据库表中.
大多数的例子我看起来好像把PHP代码搞砸到html而不是将逻辑划分到不同的文件中,就像我过去2个月里一直在做的那样.
我现在拥有的是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>
Run Code Online (Sandbox Code Playgroud)
以及CSV文件在文本中的外观的一小部分示例:
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
Run Code Online (Sandbox Code Playgroud)
或者在其他一些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
Run Code Online (Sandbox Code Playgroud)
第一行是我要将文件上传到的表的列名(在添加信息时应该忽略).
问题是,一旦将提交按钮单击到我的包含中将CSV插入表格中的PHP代码,我就不知道如何链接上传文件.
非常感谢提前
编辑:
EDIT4:
我是一个纯天才和技巧的中风Maduka能够帮助我解决这个庞然大物的问题.我不能够感谢他,以下是使用的代码,希望它有朝一日可以服务某人并为他们挽救失败的悲痛.
<?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!';
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
这是完成任务所需的基本代码,
\n\n$file = fopen($_FILES[\'csvUpload\'][\'tmp_name\'], "r");\n$i = 0;\nwhile (!feof($file)) {\n $value = (fgetcsv($file, 0, \';\'));\n if ($i > 0) {\n if ($value[0] != \'\') {\n $inserts[] = "(" . $value[0] . ","\n . $value["1"] . ","\n . $value["2"] . ","\n . $value["3"] . ","\n . $value["4"] . ","\n . $value["5"] . ","\n . $value["6"] . ")";\n }\n } elseif ($i == 0) {\n $fields = $value;\n }\n $i++;\n}\n\nmysql_query("INSERT INTO `MyTable` (`" . $fields[0] . "`,`" . $fields[1] . "`,`" . $fields[2] . "`,`" . $fields[3] . "`,`" . $fields[4] . "`,`" . $fields[5] . "`) VALUES " . implode(",", $inserts));\n\nfclose($file);\nRun Code Online (Sandbox Code Playgroud)\n\n您必须实施验证,检查文件类型和大小限制。然后将数据插入表中。我使用 MySQL 批量插入来处理大量数据。希望这可以帮助!
\n\n编辑1:
\n\n请将您的代码替换为此代码,看看它是否正常工作。
\n\n<?php\nerror_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING);\n\nmysql_connect(\'localhost\', \'root\', \'\');\nmysql_select_db("proyecto") or die(mysql_error());\n\nif (isset($_FILES[\'csvUpload\'])) {\n $errors = array();\n $allowed_ext = array(\'.csv\');\n\n $file_name = $_FILES[\'csvUpload\'][\'name\'];\n $file_ext = strtolower(end(explode(\'.\', $file_name)));\n $file_size = $_FILES[\'csvUpload\'][\'size\'];\n $file_tmp = $_FILES[\'csvUpload\'][\'tmp_name\'];\n\n if (in_array($allowed_ext) === false) {\n $errors[] = \'La extensi\xc3\xb3n del archivo no es valida.\';\n }\n if ($file_size > 10485760) {\n $errors[] = \'El archivo sobrepasa el limite de 10MB\';\n }\n if (empty($errors)) {\n\n\n $handle = fopen($file_tmp, "r");\n while (($fileop = fgetcsv($handle, ";") && fgetcsv($handle, ",")) !== false) {\n $cedula = mysql_real_escape_string($fileop[0]);\n $nombre = mysql_real_escape_string($fileop[2]);\n $apellido1 = mysql_real_escape_string($fileop[3]);\n $apellido2 = mysql_real_escape_string($fileop[4]);\n $correo = mysql_real_escape_string($fileop[5]);\n $idRol = mysql_real_escape_string($fileop[6]);\n $estado = mysql_real_escape_string($fileop[9]);\n\n\n $sq1 = mysql_query("INSERT INTO `usuarios` (cedula,nombre,apellido1,apellido2,correo,idRol,estado) VALUES (\'$cedula\',\'$nombre\',\'$apellido1\',\'$apellido2\',\'$correo\',\'$idRol\',\'$estado\')");\n }\n fclose($handle);\n if ($sq1) {\n echo \'\xc2\xa1Los usuarios han sido agregados exitosamente!\';\n }\n }\n}\n?>\n\n\n\n<form enctype="multipart/form-data" method="post" id="uploadForm">\n <input name="csvUpload" id="upload" type="file" accept=".csv" class="left" />\n <input type="submit" value="\xc2\xa1Cargar!" />\n</form>\nRun Code Online (Sandbox Code Playgroud)\n