Uploading a csv using php into MySQL and update as well
Ok so i have a database table called requests with this structure
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 |开发者_JAVA百科 float | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
Here is some example data
+----+-----------+-------------------------+------------+--------+
| 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 |
+----+-----------+-------------------------+------------+--------+
I need a way to be able to give user a way to upload a csv with the same structure and it updates or inserts based on whats in the csv. I have found many scripts online but most have a hard coded csv which is not what i need. I need the user to be able to upload the csv...Is that easy with php....
Here is an example 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
As you can see i have id 6 which is already in the database and needs to be updated..The other two will get inserted
I am not asking for someone to write the whole script but if i can get some direction on the upload and then where to go from there....thanks
Create store procedure as below and test it. It is works
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
- upload the file to a directory using move_uploaded_file
- use fgetcsv to read the uploaded csv and process each row as you like.
- delete the csv file
精彩评论