Import MySql From CSV

Continuing from my previous article about Export MySql Into CSV, I will explain about how to Import MySql From CSV. In this case, you will need to load the CSV file by using a php file that placed in the destination server. The php file will read the CSV file and then make a MySql query related to the content of the CSV file.

Here the php file:

$host = 'localhost';//host name, in this case we use localhost
$user = 'root';//user name, in this case we use root
$pass = 'password';//password, in this case we use password
$db = 'member';//declare the database that will be used

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$handle = @fopen("csv.csv", "r");
$content = '';
if ($handle) {
    while (($buffer = fgets($handle)) !== false) {
        $content .= $buffer;
    }
}
$arr1 = explode("\n",$content);
$table = '';
foreach($arr1 as $val){
	preg_match_all('/(?<!\\\)"(.*?)(?<!\\\)"|(?<!\\\)"(.*\n.*?)(?<!\\\)"/i',$val, $matches);
	$q = "INSERT INTO `member` (`member_id`, `name`, `phone`, `address`, `status`) VALUES ('".$matches[1][0]."', '".$matches[1][1]."', '".$matches[1][2]."', '".$matches[1][3]."');";//you can change this based on the table that will you insert.
	mysql_query($q);
}
fclose($handle) or die("can't close file");

You can change the $q based on the table that you want to inser. In this case, the code above will only export-import one table. However, with little bit modification you can make your own code for export-import multiple table. Good luck.

http://septiadi.com/2011/05/30/import-mysql-from-csv/

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: