Snippet
/********************************************************
** function to import a CSV file into a MySql table. The
** function expects 7 parameters:
**
** $file = The file to open
** $delimiter = What the file is delimited with
** $host = Host of the database
** $dbname = Name of the database we're using
** $username = The databases username
** $password = Users password
** $table = Name of the table we're inserting into
**
*********************************************************/
function CsvToSql($file, $delimiter, $host, $dbname, $username, $password, $table)
{
//first connection to our database
//select our database
//make sure the file exists
if(!file_exist($file)
{
echo 'The file name '. $file. ' does not exist';
}
else
{
$data = fopen($file, "r");
//now make sure the open worked
if(!$data)
{
'The file was empty';
}
//read the contents of the file int the $contents variable
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
//now close the file since we have it's contents
//start a loop
for($i = 0 ; $i < $size; i++)
{
//get the current line
$line = trim($contents[$i], $delimiter);
$split = explode($delimiter, $line);
$import = "INSERT INTO ". $table . " values('" . implode("','", $split) . "')";
echo_mysql_error();
}
}
}
Copy & Paste
|