Start csv import from specific row and end before a specific row into a database


I have a csv file from which I have to import data into a mysql db. The issue is the csv file has a few top lines with data that I don’t want to import and a few bottom lines I also don’t want to import.

I have the following code which I am currently using to import but I can’t figure out how to just import the lines I want to use.

$handle = fopen($fileDestination,“r”);

while($data = fgetcsv($handle)){
$mycnumber = mysqli_real_escape_string($conn,$data[2]);
$myamount = mysqli_real_escape_string($conn,$data[11]);
$myinstallment = mysqli_real_escape_string($conn,$data[19]);
$mydate = mysqli_real_escape_string($conn,$data[10]);

$sql = “INSERT INTO surecollect_pre_import (cnumber, amount, installment, mydate) VALUES (’”.$mycnumber."’,’".$myamount."’,’".$myinstallment."’,’".$mydate ."’);";


Please help.

So in PHP you can define certain conditions with the IF statement, and any code within would only be executed if the condition matches, e.g. if($data[0] === '123'){ mysql_query(...); }, just have a look at the manual

But you could also remove the lines afterwards with a DELETE statement and an appropriate WHERE condition

1 Like

Why waste time and resources reading the data into the database and then deleting it?

You could read each row of the csv and only if it contained the data that you want then store it in the database.

With a sample of the data some code hints could be given.

1 Like

Thank you so much.

It worked, you guys are awesome

Here is my adjustment

$handle = fopen($fileDestination,“r”);

while($data = fgetcsv($handle)){
$mycnumber = mysqli_real_escape_string($conn,$data[2]);
$mycnumber_test = substr($mycnumber, 0, 1);

 if ($mycnumber_test === 'C'){
    $mycnumber = mysqli_real_escape_string($conn,$data[2]);
    ............... and so on
Sponsor our Newsletter | Privacy Policy | Terms of Service