Here is a quick how-to to dump line items from a text file into a database. You can also use INFILE for mysql if you're using CSV. This example is if you're needing to pull line items and then manipulate the data for whatever reason prior to inserting into a MySQL database.
This uses two important functions. fopen() and fgets(). fopen() will open the file. The 'r' flag is for 'reading'. Other possible parameters would include 'a' for 'appending' and 'w' for writing. After opening a file handle to the file, use fget() to grab the contents into a buffer. These will be individual lines in the file. My example explodes on the colon, but you could parse any data at this point and assign values to local variable.
<?
$DBname = "dbname";
$DBuser = "user";
$DBpassword = "pass";
$DBserver = "localhost";
if(!$connect = mysql_connect($DBserver, $DBuser, $DBpassword)){
echo "error";exit();
}
$DB = mysql_select_db($DBname);
$handle = fopen("/var/www/localhost/htdocs/test/test.txt","r");
while(!feof($handle)){
$buffer = fgets($handle,4096);
$sections = explode(":",$buffer);
$itemOne = $sections[0];
$itemTwo = $sections[1];
$sql = "UPDATE table
SET itemOne = '".addslashes($itemOne)."'
WHERE itemTwo = '".$itemOne."'";
mysql_query($sql,$connect);
echo $itemOne." ".$itemTwo."<br>";
}
echo "Done";
fclose($handle);
?>Bookmark to:
Go Back
