问题描述
我想要PHP脚本以下列格式从CSV文件读取内容
: id,sku
1,104101
2,105213
共有1486个条目相信,最好使用for循环而不是while!EOF。
之后,我想对名为m118的数据库(catalog catalog_product_entity)执行SQL查询。 / p>
查询将类似UPDATE sku = $ csvSku WHERE id = $ csvId
和MySQL,我不知道从哪里开始编码。
fgetcsv可以用来解析CSV文件。
完整的代码如下:
<?php
$ fin = fopen('catalog_product_entity.csv','r')或die('cant open file');
$ link = mysql_connect('localhost','m118','pw');
如果(!$ link){
die('Could not connect:'。mysql_error());
}
@mysql_select_db('m118')或die('无法选择数据库');
echo连接成功< br /> \\\
;
while(($ data = fgetcsv($ fin,1000,,))!== FALSE {
$ query =UPDATE catalog_product_entity SET sku ='$ data [1]'WHERE entity_id ='$ data [0]';
mysql_query($ query);
echoRecord updated< br /> \\\
;
}
fclose($ fin);
mysql_close();
?>
I would like a PHP script to read the contents from a CSV file in the following format
id, sku
1,104101
2,105213
there are a total of 1486 entries, I believe that it's better to use a for loop instead of while !EOF.
After that, I would like to perform SQL query on a database named m118, table catalog_product_entity.
The query would be like UPDATE sku=$csvSku WHERE id=$csvId
Being a novice at both PHP and MySQL, I do not know where to start coding.
fgetcsv can be used to parse CSV files. mysql_query method could be used to perform MySQL queries.
The complete code is as follows:
<?php
$fin = fopen('catalog_product_entity.csv','r') or die('cant open file');
$link = mysql_connect('localhost', 'm118', 'pw');
If (!$link) {
die ('Could not connect: ' . mysql_error());
}
@mysql_select_db('m118') or die ('Unable to select database');
echo "Connection succeeded <br />\n";
while (($data=fgetcsv($fin,1000,","))!==FALSE) {
$query = "UPDATE catalog_product_entity SET sku='$data[1]' WHERE entity_id='$data[0]'";
mysql_query($query);
echo "Record updated <br />\n";
}
fclose($fin);
mysql_close();
?>
这篇关于编写PHP文件以从CSV读取并执行SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!