Please could somebody help me with this...

I like to make a PHP script that imports CSV data to MySQL database.

I'll be using a <form> tag to browse/select CSV file then once I submit it, it will copy the data from the CSV file to MySQL database.

I just don't have an idea yet on how to transfer data from certain file going to a database. 😕 😕 😕

    Assuming you know how to handled uploaded files, you are going to need to do one of two things:
    1) Use [man]fopen[/man] and [man]fgetscv[/man] to parse the file line by line.

    2) Call the mysql LOAD DATA INFILE query to import the file's contents. This may requiret special permissions.

      sneakyimp wrote:

      Assuming you know how to handled uploaded files, you are going to need to do one of two things:
      1) Use [man]fopen[/man] and [man]fgetscv[/man] to parse the file line by line.

      2) Call the mysql LOAD DATA INFILE query to import the file's contents. This may requiret special permissions.

      Ok, Thanks!

      One more thing... let's just say I'm already able to import the data to the database but I don't want to include the first line of the CSV file everytime I importing it...

      How will I do that?

        if you are using [man]fgetcsv[/man], you can keep a count of which line you are on and discard it if it's the first line. something like this:

        <?php
        $row = 1;
        $handle = fopen("test.csv", "r");
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if ($row == 1) {
                // skip it!
            } else {
                // insert the values in $data into your db
            }
            $row++;
        }
        fclose($handle);
        ?>
        

        If you are using an sql query with LOAD DATA INFILE then you can use the IGNORE number LINES syntax like this:

        LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test IGNORE 1 LINES;
          sneakyimp wrote:

          if you are using [man]fgetcsv[/man], you can keep a count of which line you are on and discard it if it's the first line. something like this:

          <?php
          $row = 1;
          $handle = fopen("test.csv", "r");
          while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
              if ($row == 1) {
                  // skip it!
              } else {
                  // insert the values in $data into your db
              }
              $row++;
          }
          fclose($handle);
          ?>
          

          If you are using an sql query with LOAD DATA INFILE then you can use the IGNORE number LINES syntax like this:

          LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test IGNORE 1 LINES;

          Got it!

          Thank you very much! 🙂

            Write a Reply...