将csv文件数据导入数据库
Posted
技术标签:
【中文标题】将csv文件数据导入数据库【英文标题】:Import csv file data into database 【发布时间】:2016-12-30 04:13:20 【问题描述】:如果我需要将人员的电子邮件 ID 及其姓名导入数据库,我必须编写代码,这些姓名将在 Excel 工作表上导入数据库,但面临的问题是它向我显示文件所在的无效文件.csv 格式,请帮助,我是这个概念的新手,如果我在某个地方出错了,请原谅我。
import.php
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="sel_file" size="20" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection.php");
if(isset($_POST["submit"]))
$fname = $_FILES['sel_file']['tmp_name'];
echo'Upload file name is'.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv")
$filename = $_FILES['sel_file'] ['tmp_name'];
$handle = fopen($filename, "r");
while(($data = fgetcsv($handle, 1000, ",")) !== false)
$sql = "INSERT into import_email (vault_no, name, email) values ('".$_SESSION['vault_no']."', '$data[0]', '$data[1]')";
mysql_query($sql) or die(mysql_error());
fclose($handle);
echo "Successfully imported! ";
else
echo "Invalid file!";
?>
【问题讨论】:
【参考方案1】:您使用的是临时名称而不是名称
$_FILES['sel_file'] ['tmp_name'];
把它改成:
$_FILES['sel_file'] ['name'];
$_FILE['input_file']
的例子是
[input_file] => Array
(
[name] => MyFile.jpg //<-------- This is the one you should use because it contains the extension (that you are checking for)
[type] => image/jpeg
[tmp_name] => /tmp/php/php6hst32 //<----------- this is the one you used
[error] => UPLOAD_ERR_OK
[size] => 98174
)
所以你的 PHP 部分应该是这样的:
<?php
include("connection.php");
if (isset($_POST["submit"]))
$fname = $_FILES['sel_file']['name']; // Changed only this
echo 'Upload file name is' . $fname . ' ';
$chk_ext = explode(".", $fname);
if (strtolower(end($chk_ext)) == "csv")
$filename = $_FILES['sel_file'] ['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== false)
$sql = "INSERT into import_email (vault_no, name, email) values ('" . $_SESSION['vault_no'] . "', '$data[0]', '$data[1]')";
mysql_query($sql) or die(mysql_error());
fclose($handle);
echo "Successfully imported! ";
else
echo "Invalid file!";
?>
【讨论】:
非常感谢先生..!以上是关于将csv文件数据导入数据库的主要内容,如果未能解决你的问题,请参考以下文章