I ma struggling to load information from a csv file using PHP and want to save the contents of csv (mobile phone numbers) into mysql database table.The file contents look like this:
CSV file contents ( individual record per single line with no commas)
44762126064
447508751
4474669756
44771466603
444584871
445574805
447455471039
44777451345
447460345819
44793342963
44734838672
44752845528
4474537291
44779645078
I am try to upload csv file using form and submit.The code read csv file and tries to write the content into mysql table.The problem is that code is returning all the csv records in one array element like this:
Array(
[0] => 44762126064 447508751 4474669756 44771466603 444584871 445574805 447455471039 44777451345 447460345819 44793342963 44734838672 44752845528 4474537291 44779645078
);
and inserting the whole array as one record rather one mobile number per row in mysql table.
The code :
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
# readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into mobilecsv(phoneMobile,status) values('$data[0]',0)";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
I have tried explode()
, array_slice()
etc but none of them helped me to split this array contents to save them as individual records/phone numbers in mysql database.
How can i split individual contents of first array element(as in my case) to save them as separate individual records as appearing in my CSV? I am a new programmer and would appreciate your help in this regard.Thanks
The problem is fgetcsv isn't detecting a comma which is at the heart of a COMMA separated value (CSV) file. Add this line at the top of your file after the php opening tag:
ini_set("auto_detect_line_endings", true);
change your import code to:
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while(($data = fgetcsv($handle)) !== FALSE){
$phoneMobile = $line[0];
$import="INSERT into mobilecsv(phoneMobile,status) values('$phoneMobile',0)";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.