[SOLVED] Importing Text Into MySQL
Posted: Thu Jul 22, 2004 12:37 am
I've made a text file containing a list of email addresses. It has no fields or anything, just an address on one line, then the next address on the next line. Below is the code I'm using at present, but I just see a blank screen when I load the file in my browser.
Code: Select all
<?php
$handle = fopen('addresses.txt', 'r');
// DB connection stuff
$hostname = "localhost";
$database = "******";
$username = "******";
$password = "******";
$connect = $dblink = mysql_connect($hostname, $username, $password or die(mysql_error());
mysql_select_db($database, $connect);
// Just so we can append to it later
$query = 'INSERT INTO `mailing_list` (email) VALUES ';
// Read from the file one line at a time. "Do the dirty work"
while (!feof($handle)) {
$data = rtrim(fgets($handle));
// Don't waste time with the NULL stuff, as in the automatic new line at the end of the file
if($data == NULL){
// Don't include it as data by breaking out of the while
break;
}
// Builds ONE query, much better to do if you have a large list to enter
$query .= '(''' . $data .'''), ';
}
// We're done reading from the file, so close it
fclose($handle);
// Chop off the dangling comma and whitespace of the query
$finalQuery = substr($query, 0, -2);
// If you want to, I would do this first with the actual query execution code commented out:
echo $finalQuery;
// Finally, run the query when all is good:
$result = mysql_query($finalQuery);
if($result) {
echo 'Success!';
} else {
echo '<pre>', var_dump($finalQuery), '</pre><br /><br />Something went wrong: ', mysql_error();
}
?>