The scenario is some think like this: I have to upload an examination record to MySQL via php from excel file, for this i have converted the excel file to csv so that it would be easier to upload & play around records. Every thing goes fine and the php working 100%. Problem : there are some records having "comma" so the result of this column updated as zero like 011 | Moxet Khan | BBA | 1st Semester | Fail ENG, MATH, DLD In the above example the last column shows result, in this record the result is failed in 3 subjects. Can i tune only this 5th column in php to avoid this problem here is my code: <?phpif(isset($_POST['SUBMIT'])) { $fname = $_FILES['sel_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $conn= mysql_connect('localhost','******','******') or die(mysql_error()); mysql_select_db('testing',$conn) or die(mysql_error()); echo 'Connected to Database'; $filename = $_FILES['sel_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into exams values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]'"; mysql_query($sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> <form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype='multipart/form-data'> Import File : <input type='file' name='sel_file' id='sel_file'> <input type='submit' name='SUBMIT' value='SUBMIT'> </form> Code (markup):
It would be possible to re-write this script to do some special handling of the malformed CSV file. You'd need to read the file using a funtion like file() to get an array containing each line of the file. Then use explode() on each line. For any line where you end up with too many pieces of data from explode(), you could re-assemble the last field from the extra pieces. But you shouldn't have to do any special coding in your PHP script. Whatever tool you use to convert the Excel file to CSV should automatically encode the data to account for fields that contain commas. This generally means the data field is enclosed with single or double quotation marks. So if your method of creating the CSV file does not work this way, be sure you have used the proper settings or find a different tool.