php - 使用 php 将 csv 上传到 MySQL 并更新

标签 php mysql csv import fastercsv

好的,我有一个名为 requests 的数据库表,其结构如下

mysql> desc requests;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| artist     | varchar(255) | YES  |     | NULL    |                |
| song       | varchar(255) | YES  |     | NULL    |                |
| showdate   | date         | YES  |     | NULL    |                |
| amount     | float        | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

这是一些示例数据

+----+-----------+-------------------------+------------+--------+
| id | artist    | song                    | showdate   | amount |
+----+-----------+-------------------------+------------+--------+
|  6 | Metallica | Hello Cruel World       | 2010-09-15 | 10.00  |
|  7 | someone   | Some some               | 2010-09-18 | 15.00  |
|  8 | another   | Some other song         | 2010-11-10 | 45.09  |
+----+-----------+-------------------------+------------+--------+

我需要一种方法,能够为用户提供上传具有相同结构的 csv 的方法,并根据 csv 中的内容更新或插入。我在网上找到了很多脚本,但大多数都有硬编码的 csv,这不是我需要的。我需要用户能够上传 csv...用 php 很容易吗...

这是一个 csv 示例

id  artist          song           showdate    amount
11  NewBee          great stuff    2010-09-15  12.99
10  anotherNewbee   even better    2010-09-16  34.00
6    NewArtist       New song       2010-09-25  78.99

如您所见,我的 id 6 已在数据库中,需要更新。另外两个将被插入

我并不是要求某人编写整个脚本,但如果我可以在上传方面获得一些指导,然后从那里去哪里......谢谢

最佳答案

创建如下存储过程并测试它。这是作品

CREATE proc csv

(
@id int,
@artist varchar(50),
@songs varchar(100),
@showdate datetime,
@amount float
)
as
set nocount on

if exists (select id from dummy1 where id=@id) -- Note that dummy1 as my table.

begin
update dummy1 set artist= @artist where id=@id
update dummy1 set songs=@songs where id=@id
update dummy1 set showdate=@showdate where id=@id
update dummy1 set amount=@amount where id=@id
end
else
insert into dummy1  (artist,songs,showdate,amount)values(@artist,@songs,@showdate,@amount)
Go

关于php - 使用 php 将 csv 上传到 MySQL 并更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4066505/

相关文章:

session - 将 php.ini 的 session.auto_start 设置为 1 是否被认为是不好的做法?

MySQL 查询每月总销售额和付款类型

javascript - Highcharts:对多个 CSV 文件中的 x 轴值进行排序

scala - CsvParser 不适用于缺少双引号的情况

PHP类别树递归

php - 如何在 Controller 中正确执行 symfony2 中的 If 语句

php、MySql查询,两个COUNT一个GROUP BY

python - Numpy:加载多个 CSV 文件作为字典

php - PHP x MYSQL 使用 UTF8_encode() 和 UTF8_decode() 时出现重音错误?

mysql - 将查询存储在bash中的数组中