Blog

Back 0 Comments

Tutorial: Import a CSV File Using PHP and MySQL


The following code should help beginner PHP/MySQL developers who are looking for an easy way to import a CSV or comma delimited file into a mysql database.  This example adds new contacts into the contacts table from an uploaded CSV file, populating the following three fields: (contact_first, contact_last, contact_email).

Click to view files:

I've included the PHP code below that 'does all the work'.  Click the 'import.php' link above to view the full code.

    //get the csv file
    $file = $_FILES[csv][tmp_name];
    $handle = fopen($file,"r");
   
    //loop through the csv file and insert into database
    do {
        if ($data[0]) {
            mysql_query("INSERT INTO contacts_tmp (contact_first, contact_last, contact_email) VALUES
                (
                    '".addslashes($data[0])."',
                    '".addslashes($data[1])."',
                    '".addslashes($data[2])."'
                )
            ");
        }
    } while ($data = fgetcsv($handle,1000,",","'"));
    //



Your comment has been posted....
Post a comment

Name


Email (won't be published)


Comments