使用php从csv文件填充数据库

时间:2011-10-31 01:23:29

标签: php

如何使用PHP代码从csv文件中的info填充数据库?我需要练习使用php来进行数据库调用,但此刻,我有权访问的是这个csv文件......

3 个答案:

答案 0 :(得分:1)

设计考虑因素: 您可能不希望使用像file_get_contents这样的函数一次将整个文件加载到内存中。使用大文件会占用所有可用内存并导致问题。相反,像亚当建议的那样,一次读一行。

fgetcsv at php manual

//Here's how you would start your database connection
mysql_connect($serverName, $username, $password);
mysql_select_db('yourDBName');

//open the file as read-only
$file = fopen("file.csv", "r");

// lineLength is unlimited when set to 0
// comma delimited
while($data = fgetcsv($file, $lineLength = 0, $delimiter = ",")) {
   //You should sanitize your inputs first, using a function like addslashes
   $success = mysql_query("INSERT INTO fileTable VALUES(".$data[0].",".$data[1].")");
   if(!$success) {
     throw new Exception('failed to insert!');
   }
}

答案 1 :(得分:0)

答案 2 :(得分:0)

使用内置的PHP函数读取CSV并写入输出文件。然后,您可以将SQL导入数据库。这适用于任何类型的数据库。

不要忘记逃避您正在使用的任何字符串。在这个例子中,我使用了sqlite_escape_string()来实现这个目的。

$fd = fopen("mydata.csv", "r");
$fdout = fopen("importscript.sql","w");

while(!feof($fd))
{
    $line = fgetcsv($fd, 1024); // Read a line of CSV

    fwrite($fdout,'INSERT INTO mytable (id,name)'
                 .'VALUES ('.intval($line[0]).",'".sqlite_escape_string($line[1])."');\r\n";
}

fclose($fdout);
fclose($fd);