Monday 3 September 2018

How to exclude the column header from the CSV file in PHP?

When my client's are giving their inputs into the Excel file, they need the column header. But when they export the file into CSV (.csv) it includes the column heads into it. That's problem.

+---------+--------+-------------+
| Post id |  Name  | Designation |
+---------+--------+-------------+
    101     noYon      designer
    102     nakib     accountant
    103     nishi      developer
+---------+--------+-------------+
In my CSV (comma delimited) I got:
Post id,Name,Designation
101,noYon,designer
102,nakib,accountant
103,nishi,developer
I need to exclude the column heads (the first row) from the CSV when uploading it to MySQL using PHP.
Is there any way?

A simple solution: read the first line and discard it before reading the rest of the file line by line in a loop:
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
fgetcsv($handle);  // Discard first line. If we know the maximum line length
                   // add it as second argument: it's slightly faster 

while( $data = fgetcsv( $handle) ) {
   $query = mysqli->query( "INSERT INTO table (post_id,name,designation) VALUES ('".
                implode($data,"','")."'";
}

A faster solution which I've not coded here: append multiple sets of values to the INSERT like this:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

0 comments:

Post a Comment