samuel_lopez Posted November 5, 2015 Share Posted November 5, 2015 hi. I have a problem on importing csv file using php.Below code is working but its inserting the first line(header).I don't need to import also headers.How can I prevent the code to save headers.Your response is much appreciated.Thank you <?php include 'config.php'; if(isset($_POST["import"])){ echo $filename=$_FILES["file"]["tmp_name"]; if($_FILES["file"]["size"] > 0) { $file = fopen($filename, "r"); while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) { $sql = $mysqli->query("INSERT INTO table (name,age) VALUES ('$emapData[1]','$emapData[2]')") or die(mysqli_error($mysqli)); if(!$sql) { echo "<script type=\"text/javascript\"> alert(\"Invalid File:Please Upload CSV File.\"); window.location = \"import_student.php\" </script>"; } } fclose($file); echo "<script type=\"text/javascript\"> alert(\"CSV File has been successfully Imported.\"); window.location = \"import_student.php\" </script>"; mysqli_close($mysqli); } } ?> Quote Link to comment Share on other sites More sharing options...
Barand Posted November 5, 2015 Share Posted November 5, 2015 You could check if the age value is numeric. If it isn't (header), skip the insert. Quote Link to comment Share on other sites More sharing options...
QuickOldCar Posted November 5, 2015 Share Posted November 5, 2015 It's usually best to save a date of birth versus an age. Quote Link to comment Share on other sites More sharing options...
benanamen Posted November 5, 2015 Share Posted November 5, 2015 (edited) $row = 1; if (($handle = fopen("Your_File.csv", "r")) !== FALSE) { fgetcsv($handle, 10000, ","); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } Edited November 5, 2015 by benanamen Quote Link to comment Share on other sites More sharing options...
benanamen Posted November 5, 2015 Share Posted November 5, 2015 (edited) * Got locked out of previous post. If your csv ALWAYS has a header row you can use the code I just posted. To do it using file: $file = file("Your_File.csv"); array_shift($file); foreach($file as $f){ echo $f."<br />"; } Edited November 5, 2015 by benanamen Quote Link to comment Share on other sites More sharing options...
samuel_lopez Posted November 5, 2015 Author Share Posted November 5, 2015 Hi to all, Thank you for your suggestion and help. Will now apply this fix. Thanks again. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.