CSV to MySql

Page 1 of 1

1 Replies - 584 Views - Last Post: 17 February 2011 - 12:50 AM

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1658
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

CSV to MySql

Posted 03 July 2009 - 03:53 PM

Description: Instructions are in the comments header of the snippetSnippet to take the contents from a CSV file and insert it into a MySQL database table.
/********************************************************
** 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
	$conn = mysql_connect($host, $username, $password) or die();
	//select our database
	mysql_select_db($dbname);
	
	//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
		fclose($file);
		
		
		//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) . "')";

			if(!mysql_query($import))
				echo_mysql_error();			
		}
		
	}
	
	mysql_close($conn);
}


Is This A Good Question/Topic? 0
  • +

Replies To: CSV to MySql

#2 vigoloubev  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 16
  • Joined: 17-February 11

Re: CSV to MySql

Posted 17 February 2011 - 12:50 AM

every time you start a loop it calls mysql's INSERT INTO. what about one time INSERT?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1