load csv into mysql_Load a csv file into mysql via php

最佳答案

It can be done by using the fgetcsv PHP function.

Afterwards, use the Mysql INSERT function in order to save that data in the Database.

参考答案2

MySQL has a feature LOAD DATA INFILE, which allows it to import a CSV file directly in a single SQL query, without needing it to be processed in a loop via your PHP program at all.

Simple example:

$query = <<

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);

?>

It's as simple as that.

No loops, no fuss. And much much quicker than parsing it in PHP.

Hope that helps

author

参考答案3

Give this a try. This uses a function to read the lines of the file into an array of strings, then loops through each line and stores the column values to a table. Obviously you will need to insert your db connection settings and proper query.

function loadData()

{

$lines = readInputFromFile("myCSV.csv");

for ($i = 0; $i < count($lines); $i++)

(

$columns = explode(",", $lines[$i]);

$conn = new PDO("mysql:host=YOUR_HOST;port=YOUR_PORT;dbname=YOUR_DBNAME", "UserName", "Password");

$query = "INSERT INTO MYTABLE VALUES ('".$columns[0]."', '".$columns[1]."', '".$columns[2]."')";

$stmt = $conn->prepare($query);

$stmt->execute();

)

}

function readInputFromFile($file)

{

$fh = fopen($file, 'r');

while (!feof($fh))

{

$ln = fgets($fh);

$parts[] = $ln;

}

fclose($fh);

return $parts;

}

参考答案4

If you are looking for the easiest method to import csv file into mysql, then go with following:

Eg:

LOAD DATA LOCAL INFILE 'import.csv' INTO TABLE from_csv FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (si, distro, available);

For more reading:

参考答案5

see the code below

csv2sql("pre_employee","ch_data.csv");

function csv2sql($table_name,$csvname)

{

$fl=fopen($csvname,r);

//if(!file_exists('a.txt'))

//{

$flw=fopen("a.txt",'w');

//}

$sql='';

$i=2;

//echo $csvname.$data=fgetcsv($fl,1000,",");die();

while(($data=fgetcsv($fl,1000,","))!=false)

{

$sql.="insert into ".$table_name." values('".$data[0]."','".$data[2]."','".$data[3]."');".chr(13);

$i++;

}

//echo $sql;

fwrite($flw,$sql);

fclose($flw);

fclose($fl);

}

a.txt is the filename saving your sql. nor import this txt file to your mysql database.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值