I have a .csv file data like that
Date,Name,Call Type,Number,Duration,Address,PostalCode,City,State,Country,Latitude,Longitude
"Sep-18-2013 01:53:45 PM","Unknown","outgoing call",'123456',"0 Secs","null","null","null","null","null",0.0,0.0,,,
"Sep-18-2013 01:54:14 PM","Unknown","outgoing call",'1234567890',"0 Secs","null","null","null","null","null",0.0,0.0,,,
"Sep-18-2013 01:54:37 PM","Unknown","outgoing call",'14772580369',"1 Secs","null","null","null","null","null",0.0,0.0,,,
and I'm using the following code to insert the data into database
$sql = "LOAD DATA INFILE `detection.csv`
INTO TABLE `calldetections`
FIELDS TERMINATED BY '".@mysql_escape_string(",").
"` OPTIONALLY ENCLOSED BY `".@mysql_escape_string(""").
"` OPTIONALLY ENCLOSED BY `".@mysql_escape_string("'").
"` ESCAPED BY `".@mysql_escape_string("\").
"` LINES TERMINATED BY `".",,,\r\n".
"`IGNORE 1 LINES `"
."(`date`,`name`,`type`,`number`,`duration`,`addr`,`pin`,`city`,`state`,`country`,`lat`,`log`)";
$res = @mysql_query($con,$sql);
but nothing is inserted; where is the mistake?
If you'd do
echo($sql);
before you execute it you'd see that syntax of your query is incorrect for following reasons:Filename should be enclosed in quotes rather than backticks because it's a string literal not an identifier.
There is absolutely no need to call
mysql_escape_string()
to specify a delimiter inFIELDS TERMINATED BY
andENCLOSED BY
andESCAPED BY
clauses.You overuse backticks. In fact in your case, since there are no reserved words used, you ditch them all. They only add clutter.
At the end of the very first line of your CSV file you have to have
,,,
because you use them as part of a line delimiter. If you won't do that you'll skip not only first line but also second one that contains data.You can't use
ENCLOSED BY
clause more than once. You have to deal withNumber
field in a different way.Looking at your sample rows IMHO you don't need
ESCAPED BY
. But if you feel like you need it use it like thisESCAPED BY '\'
.That being said a syntacticly correct statement might look like this
Now IMHO you need to transform quite a few fields while you load them:
if
date
in your table is ofdatetime
data type then it needs to be transformed, otherwise you'll get an erroryou have to deal with single qoutes around values in
Number
fieldyou most likely want to change
"null"
string literal to actualNULL
foraddr, pin, city, state, country
columnsif duration is always in seconds then you can extract an integer value of seconds and store it that way in your table to be able to easily aggregate duration values later.
That being said a useful version of the statement should look something like this
Below is the result of executing the query on my machine
And finally in php assigning a query string to
$sql
variable should look like this