Csv File To Mysql Table

Discussion in 'PHP' started by worldart, Feb 18, 2013.

  1. #1
    Hello people

    I have a csv file which is having records, I have created table as per the comma seperated values. How can i insert data from csv file to the mysql table?

    Is there any easiest way?
     
    worldart, Feb 18, 2013 IP
  2. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #2
    Cant you just Import the file through phpmyadmin
     
    MyVodaFone, Feb 18, 2013 IP
  3. Pro Designz

    Pro Designz Greenhorn

    Messages:
    28
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    23
    #3
    You can import csv file to the mysql using phpmyadmin or you can do it like following command on mysql prompt

    load data local infile "filename.csv" into table yourtable fields terminated by ',' enclosed by ' " ' lines terminated by '\n' (fieldname1,fieldname2....)
     
    Pro Designz, Feb 18, 2013 IP
  4. tyteen4a03

    tyteen4a03 Member

    Messages:
    30
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    45
    #4
    If you have to import it to PHP without phpMyAdmin (for the love of God please just use phpMyAdmin) and you know the fields, you can make use of the PHP CSV library. Here's a code I wrote a while ago that allows you to import CSV data:

    if (file_exists($file)) {
      $csvdb = fopen($file, "r");
    } else {
      $error = "No file was uploaded.";
      die();
    }
    $i = -1; // Skip first rows - header
    $valuesbit = "";
    $rows = array();
    while (($row = fgetcsv($csvdb)) !== false) {
      $i++;
      if ($i == 0) { // Don't care about header row
          continue;
      }
      // Data cleaning
      $somefield = mysql_real_escape_string($row[0]) // The column it is in for this row, a 1D array
      $another = mysql_real_escape_string($row[1])
      $valuesbit .= "('{$somefield}', '{$another}', '{$blah}', {$welp}, {$stuff}, {$happens}),";
    }
    $valuesbit = mb_substr($valuesbit, 0, -1); // Hack
    $q = mysql_query("INSERT INTO sometable (somefield, another, blah, welp, stuff, happens) VALUES " . $valuesbit);
    if (!$q) {
      $error = "A database error occured. Please try again later.";
    } else {
      echo ("Success!");
    }
    fclose($csvdb);
    PHP:
     
    tyteen4a03, Feb 19, 2013 IP