我在尝试从CSV导入数据时遇到了一些问题,并且有一些问题我还没有设法自己解决。
首先,这是我的代码,以帮助将事情放在透视中(整理一下,删除CSS和数据库连接):
<body>
<div id="container">
<div id="form">
<?php
$deleterecords = "TRUNCATE TABLE tablename"; //empty the table of its current records
mysql_query($deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded
successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into importing(text,number)values('$data[0]','$data[1]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
//view upload form
} else {
print "Upload new csv by browsing to file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
</div>
</div>
</body>
它基本上是对我在各种方法中多次尝试后发现的一个例子的改编。
我的CSV有两列数据,第一列是文本,第二列是整数 数据库中的表也有两列,第一列称为“text”,第二列称为“number”
所以我的问题是:
我认为这涵盖了一切,提前感谢您的帮助!
编辑:
刚刚对10,000条记录上传进行了测试并得出错误:
“致命错误:超过30秒的最长执行时间”
有什么想法吗?
答案 0 :(得分:65)
前几天我回答了一个几乎完全相同的问题:Save CSV files into mysql database
MySQL有一个功能LOAD DATA INFILE
,允许它直接在单个SQL查询中导入CSV文件,而不需要通过PHP程序循环处理它。
简单示例:
<?php
$query = <<<eof
LOAD DATA INFILE '$fileName'
INTO TABLE tableName
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field1,field2,field3,etc)
eof;
$db->query($query);
?>
就这么简单。
没有循环,没有大惊小怪。并且很多比在PHP中解析它更快。
MySQL手册页:http://dev.mysql.com/doc/refman/5.1/en/load-data.html
希望有所帮助
答案 1 :(得分:6)
$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0){
$import="INSERT into importing(text,number)values('".$data[0]."','".$data[1]."')";
mysql_query($import) or die(mysql_error());
}
$i=1;
}
答案 2 :(得分:2)
letsay $ infile = a.csv //文件需要导入。
class blah
{
static public function readJobsFromFile($file)
{
if (($handle = fopen($file, "r")) === FALSE)
{
echo "readJobsFromFile: Failed to open file [$file]\n";
die;
}
$header=true;
$index=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
// ignore header
if ($header == true)
{
$header = false;
continue;
}
if ($data[0] == '' && $data[1] == '' ) //u have oly 2 fields
{
echo "readJobsFromFile: No more input entries\n";
break;
}
$a = trim($data[0]);
$b = trim($data[1]);
if (check_if_exists("SELECT count(*) FROM Db_table WHERE a='$a' AND b='$b'") === true)
{
$index++;
continue;
}
$sql = "INSERT INTO DB_table SET a='$a' , b='$b' ";
@mysql_query($sql) or die("readJobsFromFile: " . mysql_error());
$index++;
}
fclose($handle);
return $index; //no. of fields in database.
}
function
check_if_exists($sql)
{
$result = mysql_query($sql) or die("$sql --" . mysql_error());
if (!$result) {
$message = 'check_if_exists::Invalid query: ' . mysql_error() . "\n";
$message .= 'Query: ' . $sql;
die($message);
}
$row = mysql_fetch_assoc ($result);
$count = $row['count(*)'];
if ($count > 0)
return true;
return false;
}
$infile=a.csv;
blah::readJobsFromFile($infile);
}
希望这会有所帮助。
答案 3 :(得分:2)
set_time_limit(10000);
$con = mysql_connect('127.0.0.1','root','password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$fp = fopen("file.csv", "r");
while( !feof($fp) ) {
if( !$line = fgetcsv($fp, 1000, ';', '"')) {
continue;
}
$importSQL = "INSERT INTO table_name VALUES('".$line[0]."','".$line[1]."','".$line[2]."')";
mysql_query($importSQL) or die(mysql_error());
}
fclose($fp);
mysql_close($con);
答案 4 :(得分:0)
我认为解析csv的主要事项是遵循一些简单的规则:
a)这是一个很容易打开的文本文件 b)每行由行结束确定\ n因此首先将字符串拆分为行 c)每行/每行都有由逗号确定的列,因此将每行分开以获得列数组
have a read of this post看看我在说什么
一旦掌握了它并且变得非常有用,它实际上很容易做到。
答案 5 :(得分:-1)
数据库连接:
try {
$conn = mysqli_connect($servername, $username, $password, $db);
//echo "Connected successfully";
} catch (exception $e) {
echo "Connection failed: " . $e->getMessage();
}
读取 CSV 文件并上传到数据库中的表格的代码。
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE) {
$sql = "INSERT into db_table
values ('','" . $getData[1] . "','" . $getData[2] . "','" . $getData[3] . "','" . $getData[4] . "','" . $getData[5] . "','" . $getData[6] . "')";
$result = mysqli_query($conn, $sql);
if (!isset($result)) {
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.
window.location = \"home.do\"
</script>";
} else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"home.do\"
</script>";
}
}
fclose($file);