I have this code and it works well when I import only three fields, but when I try to import more than 3 it does not work.
mysql_query("INSERT INTO forms (id, created_time, ad_id, ad_name, adset_id, adset_name, campaign_id, campaign_name, form_id, is_organic, specialist, full_name, email, city, country, date_of_birth, phone_number) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."',
'".addslashes($data[5])."',
'".addslashes($data[6])."',
'".addslashes($data[7])."',
'".addslashes($data[8])."',
'".addslashes($data[9])."',
'".addslashes($data[10])."',
'".addslashes($data[11])."',
'".addslashes($data[12])."',
'".addslashes($data[13])."',
'".addslashes($data[14])."',
'".addslashes($data[15])."',
'".addslashes($data[16])."',
'".addslashes($data[17])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
try this its work for you
while ($data = fgetcsv($handle, 1000, ","));
instead of
while ($data = fgetcsv($handle,1000,",","'"));
What is addslashes()
doing in this code? There's only one thing you need to escape when talking to a database, and that's single quotes (see mysql_real_escape_string()
, mysqli_real_escape_string(), etc.) addslashes
is for generating html, so it scribbles on your data in ways that you'll notice when it's too late. Since we're on it, you also shouldn't use the long-obsoleted mysql_*
functions. Didn't you see the big red (ok pink) Warning in the documentation of mysql_query()
? Use mysqli
, which is barely different if you don't use the object-oriented style. Third, you should use "prepared queries", not build the strings yourself. Much safer this way. See here for an example.
So, finally to your question. To build a long string from lots of array elements, you could use a loop to append each element in turn. But a better way is to use implode
: It combines array elements into a single string, with your choice of connecting string.
// Escape the first 18 columns of $data
$escaped = array_map("mysqli_real_escape_string", array_slice($data, 0, 18));
// Now pack them into the insert query
$querystring = "INSERT INTO forms (id, created_time, ad_id, ad_name, adset_id, adset_name, campaign_id, campaign_name, form_id, is_organic, specialist, full_name, email, city, country, date_of_birth, phone_number)
VALUES (" . implode(",", $escaped) . ")";