Tuesday, March 1, 2011

how to php code in csv ?

This is a simple script that will allow you to import csv data into your database. This comes handy because you can simply edit the appropriate fields, upload it along with the csv file and call it from the web and it will do the rest.
It allows you to specify the delimiter in this csv file, whether it is a coma, a tab etc. It also allows you to chose the line separator, allows you to save the output to a file (known as a data sql dump).
It also permits you to include an empty field at the beginning of each row, which is usually an auto increment integer primary key.
This script is useful mainly if you don’t have phpmyadmin, or you don’t want the hassle of logging in and prefer a few clicks solution, or you simply are a command prompt guy.
Just make sure the table is already created before trying to dump the data.


$chunksize = 1*(1024*1024);
$file = fopen($csvfile,"rb");
if(!$file) {
echo "Error opening data file.\n";
exit;
}

$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());
$lines = 0;
$queries = "";
while (!feof($file)) {
$csvline = fgets($file,$chunksize);
$lines++;
if($lines < 2) continue;
$line = trim($csvline," \t");
$line = str_replace("\r","",$line);
/************************************************************************************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************************************************************************************/
$line = str_replace("'","\'",$line);
/***********************************************************************************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
$query = "insert into $databasetable values('$linemysql');";
if($save) $queries .= $query . "\n";
@mysql_query($query);
echo $lines."\n";
}
fclose($file);
$lines -= 3;
@mysql_close($con);
Thank you,

No comments:

Post a Comment