简体   繁体   English

以CSV格式导出所选行并导回相同的CSV文件以更新PHP / MySQL中的选定行

[英]Export selected rows in CSV and import back same CSV file to update selected rows in PHP/MySQL

I have a mysql table with following columns: 我有一个包含以下列的mysql表:

filterid    productid   value   groupid

I want to export the rows of this table (Only selected rows) to a CSV file. 我想将此表的行(仅选定的行)导出到CSV文件。 I know how to do the exporting part. 我知道如何做出口部分。

For example, if I have exported the rows based on product ID, let say exported rows are: 例如,如果我已根据产品ID导出行,请说导出的行为:

4   13307   USA|Quebec|Rest of Canada   750
9   15963   USA|Quebec|Rest of Canada   1
9   13618   USA|Quebec|Rest of Canada   1
9   16210   USA|Quebec|Rest of Canada   1
9   16666   USA|Quebec|Rest of Canada   1

Out of total 100 rows. 总共100行。

Now, I have exported this content into a CSV file and want to import it back to my mysql table where it should update only rows matching with the product id's which are in my exported CSV file without disturbing rest of the table content. 现在,我已将此内容导出到CSV文件中,并希望将其导回到我的mysql表,在该表中,它应仅更新与导出的CSV文件中的产品ID匹配的行,而不会干扰其他表格内容。

Is it possible to do that? 有可能吗?

After googling, what I found is that I can import a CSV to a table using this code 谷歌搜索后,我发现我可以使用此代码将CSV导入表格

LOAD DATA LOCAL INFILE 'filename.csv' INTO TABLE my_table FIELDS
TERMINATED BY ',' 
ENCLOSED BY '' 
LINES TERMINATED BY '\n'

Please suggest a way to achieve this. 请建议一种方法来实现这一目标。

I can provide you with more sample code if you need. 如果您需要,我可以为您提供更多示例代码。

Thank You! 谢谢!

I think he was asking the question because he didn't know how to use INFILE with a WHERE clause: 我想他是在问这个问题,因为他不知道如何使用INFILEWHERE子句:

Now, I have exported this content into a CSV file and want to import it back to my mysql table where it should update only rows matching with the product id's which are in my exported CSV file without disturbing rest of the table content. 现在,我已将此内容导出到CSV文件中,并希望将其导回到我的mysql表,在该表中,它应仅更新与导出的CSV文件中的产品ID匹配的行,而不会干扰其他表格内容。

If you want to use a script to do what you mentioned, you can try the following: 如果要使用脚本执行上述操作,可以尝试以下操作:

// set up your database connection
$fp = fopen('your_csv_file.csv','r') or die("**! can't open file\n\n");

// loop through your lines
while($csv_line = fgetcsv($fp,1024)) {

    $filterid = $csv_line[0];
    $productid = $csv_line[1];
    $value = $csv_line[2];
    $groupid = $csv_line[3];

    $update =  "UPDATE your_table(filterid, productid, value, groupid) ";
    $update .= "VALUES('$filterid', '$productid'; '$value'; '$goupid') WHERE productid='$productid'";

    // run $update on your database
}

fclose($fp) or die("**! can't close file\n\n");

It should at least point you in the right direction.. 它至少应该指向正确的方向..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM