I've been working on this for 3 days! It all works but I'm stuck at the last bit - removing the header row from the csv file. I've done a search and found a similar item
http://www.phpbuilder.com/board/showthread.php?t=10322740&highlight=fgetcsv+header
with an answer but it didn't work for me. (mysql error mismatch in row numbers )

In the following, I'm getting a csv file posting to a job board, splitting it into jobs and clients and inserting the data into two tables of a database.

How do I get rid of the header??


<?php


$today = date('Y-m-d'); // adds a date to a table

$gotfile = "uploads/".$_GET['id']; // getting the csv file



$row = 1;
$handle = fopen($gotfile, "r");

while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {

$jobset = array_slice($data, 0, 12); // slicing the array for the jobs
$clientset = array_slice($data, 12); // slicing the array for the clients

$fieldnumber = count($jobset); // setting the counter limit
$fieldnumber2 = count($clientset); // setting the counter limit



/* date + random number for account number */
$num = rand(0,99999);
$ref = date("dmy")."-". $num ; 

 $insertquery =  "INSERT INTO mydatabase.jobs (job_ref, job_title, job_salary, job_salaryrota, job_benefits, job_type, job_cat, job_town, job_region, job_postcode, job_desc, job_closingdate, accountno, job_date) VALUES (";

 $insertquery2 =  "INSERT INTO mydatabase.clients (client_email, client_name, client_company, client_address, client_postcode, client_phone, mailing_list, accountno) VALUES (";

$row++;


 for ($i=0; $i < $fieldnumber; $i++) { // loops through the FIELDS

  $insertquery.= "'" .$jobset[$i] . "',";


}

$insertquery.= "'$ref','$today');"; mysql_query($insertquery) or die(mysql_error());


// second loop
for ($i=0; $i < $fieldnumber2; $i++) { // loops through the FIELDS

  $insertquery2.= "'" .$clientset[$i] . "',";

}

$insertquery2.= "'$ref');"; mysql_query($insertquery2) or die(mysql_error());
}
fclose($handle);
?> 




    If we assume that the first row retrieved will be the headers, then a simple solution is to retrieve it and ignore it before starting your loop:

    // don't do anything with first row:
    $data = fgetcsv($handle, 5000, ",")
    // now retrieve and process the data:
    while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
    // etc....
    

      hmmm... interesting, thanx NogDog.
      but it gives the error
      Parse error: syntax error, unexpected T_IS_NOT_IDENTICAL
      (for the line beginning: while...)

      which I don't think I've seen before.

        I forgot the semi-colon at the end of the first fgetcsv line.

          yup, I spotted that.

          Hang on - It's working!!!

          thank you sooooooooooo much!
          thank you sooooooooooo much!
          thank you sooooooooooo much!

            Write a Reply...