PHP Functions to Import/Export CSV data


This function has just one argument – the query that returns the necessary data to be exported.
Example: CSVExport("SELECT name,username,email,url FROM User WHERE status=1");


This will upload a CSV file and import the data into the specified table. This function must have the following arguments…

The name of the table the data must be imported to
An array of fields that will be used
The name of the CSV file field

Example: CSVImport("User", array('name','username','email','url'), "csv_file");


<?php//Get the result of the query as a CSV stream.
function CSVExport($query) {
$sql_csv mysql_query($query) or die("Error: " mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer
$row mysql_fetch_row($sql_csv)) {
'"' stripslashes(implode('","',$row)) . "\"\n";
//Import the contents of a CSV file after uploading it
//Aruguments : $table - The name of the table the data must be imported to
//                $fields - An array of fields that will be used
//                $csv_fieldname - The name of the CSV file field
function CSVImport($table$fields$csv_fieldname='csv') {
$_FILES[$csv_fieldname]['name']) return;

    $handle fopen($_FILES[$csv_fieldname]['tmp_name'],'r');
$handle) die('Cannot open uploaded file.');

    $row_count 0;
$sql_query "INSERT INTO $table("implode(',',$fields) .") VALUES(";

    $rows = array();

    //Read the file as csv
while (($data fgetcsv($handle1000",")) !== FALSE) {
$data as $key=>$value) {
$data[$key] = "'" addslashes($value) . "'";
$rows[] = implode(",",$data);
$sql_query .= implode("),("$rows);
$sql_query .= ")";

    if(count($rows)) { //If some recores  were found,
        //Replace these line with what is appropriate for your DB abstraction layer
mysql_query("TRUNCATE TABLE $table") or die("MySQL Error: " mysql_error()); //Delete the existing records
mysql_query($sql_query) or die("MySQL Error: " mysql_error()); // and insert the new ones.

        print 'Successfully imported '.$row_count.' record(s)';
    } else {
'Cannot import data - no records found.';


About amitsonikhandwa
I am a web developer working in PHP and MYSQL with AJAX, jQuery and JavaScript. I am in web development since 2007.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s