Xx...Tazer...xX Owner
Posts : 1239 T®ue Points : 1102678 T®ue Reputation : 40 Join date : 2009-09-02 Age : 31 Location : Chicago,Illinois
| Subject: CHANGE CSV TO MYSQL - PHP SNIPPET Sun Jul 11, 2010 7:28 pm | |
| today I will you guys a snippet of changing CSV to MySQL. This snippet takes the contents from a CSV file and insert it into a MySQL database table. In this part of the topic, I will post all of the directions needed in order to know this procedure. If you had any problems, please contact me and I will be gladly to help, also you can review in my Quick References of advanced/Basic PHP for any trouble. Here are the following instructions or directions.
Instructions of Functions of parameters: Additional directions will be added right next to this symbol---> "//" as a sentence.
The function to import a CSV file into a MySQL table. The function expects 7 parameters, so here are the following:
$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.
Ok here is the the source file:
CSV to MySQL source file
Code: [Select] 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); } | |
|