Maria Nolorbe Maria Nolorbe - 1 month ago 10
MySQL Question

exclude row 1 when importing CSV file to MYSQL using php

I have the following code that imports a CSV file into MYSQL table. The only problem is that it also import the header row. How can I alter the below code so that it doesn't include the top row.

I looked around and found 'IGNORE 1 LINES', but have yet to get it working.

Also, what does that '500' mean?

//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));

// open the csv file
$fp = fopen($filename,"r");

//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
//insert csv data into mysql table
$sql = "INSERT INTO table92108 (date,filename,directory,type,email) VALUES('" . implode("','",$row) . "')";
if(!mysqli_query($connection, $sql))
{
die('Error : ' . mysqli_error());
}
}

fclose($fp);

//close the db connection
mysqli_close($connection);
?>


Here is my second attempt based on answer below, but still doesn't work. What did I do wrong???

//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));

// open the csv file
$fp = fopen($filename,"r");

//parse the csv file row by row
$count = 0;
while (($row = fgetcsv($fp, 500, ",")) !== FALSE) {
$count++;
if ($count == 1) { continue; }

{
//insert csv data into mysql table
$sql = "INSERT INTO table92108 (date,filename,directory,type,email) VALUES('" . implode("','",$row) . "')";
if(!mysqli_query($connection, $sql))
{
die('Error : ' . mysqli_error());
}
}

fclose($fp);

//close the db connection
mysqli_close($connection);

Answer

Try this, use counter variable $count and skip row when $count = 1

//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));

// open the csv file
$fp = fopen($filename,"r");

$count = 0;
while (($row = fgetcsv($fp, 500, ",")) !== FALSE) {
    $count++;
    if ($count == 1) 
    { 
        continue; 
    }
    else
    {
        //insert csv data into mysql table
        $sql = "INSERT INTO table92108 (date,filename,directory,type,email) VALUES('" . implode("','",$row) . "')";
        if(!mysqli_query($connection, $sql))
        {
            die('Error : ' . mysqli_error());
        }
    }
}
fclose($fp);

//close the db connection
mysqli_close($connection);
Comments