php读取csv更新mysql,使用PHP从CSV更新MySql表

I need a PHP script which will update existing MySQL table getting data from a CSV. Table field hasweb need to be updated comparing a field consultant_id.

So MySql query should be

UPDATE user_data

SET hasweb="something"

WHERE consultant_id = "something";

Please help me to write a PHP script which can execute this query as many times as needed, depending upon CSV data.

解决方案

I have written little php scripts to accomplish this many times and there are many ways go to about it:

The best according to my experience is to use CSV functions provided by PHP, take a look at fgetcsv(), because manually opening file and reading it line by line and parsing can cause complications.

Now you just loop through all the rows in csv and prepare query dynamically and execute it, for example (assuming that column 0 has IDs and column 1 has "hasweb")

if (($handle = fopen("input.csv", "r")) !== FALSE)

{

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)

{

mysql_query(UPDATE user_data SET hasweb="{$data[1]}" WHERE consultant_id = "{$data[0]}");

}

fclose($handle);

}

?>

Hope that helps. If still stuck, Please ask me :)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值