Forum Moderators: coopster

Message Too Old, No Replies

reading from text file and storing in MySQL

reading txt file and storing it in an array to inseart in MySQL database

         

Mitch888

6:31 am on Jan 23, 2004 (gmt 0)

10+ Year Member



Hello,

I have a text file consist of 10 digit phone numbers one number per line like this:
5553332244
5553332244
5553332244
5553332244
etc…

How do I read a text file line by line and populate the data into an array to store it into a MySQL database? My database is below:

CREATE TABLE `friendstel` (
`id` bigint(6) NOT NULL auto_increment,
`tel` varchar(10) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;

I successfully done the following to read text file line by line:

<?
$fp = fopen ("friendstel.txt", "r");
while (!feof ($fp)) {
$content = fgets( $fp, 4096 );
echo "$content<br>";
}
fclose ($fp);
?>

How do I store the content of the text file in the MySQL database?

Any help would be appreciated.

Thank you

coopster

1:44 pm on Jan 23, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You will be using the INSERT [mysql.com] statement:

<?
$sql_static = 'INSERT INTO friendstel (id, tel) VALUES(NULL, ';
$fp = fopen ("mitch888.txt", "r");
while (!feof ($fp)) {
$content = fgets( $fp, 4096 );
$sql = $sql_static . $content .')';
// echo "$sql<br />";
mysql_query($sql);
}
fclose ($fp);
?>

I build a static statement first so my PHP script doesn't have to structure that variable on every iteration of the loop. A NULL value on an AUTO_INCREMENT [mysql.com] field will do exactly what it is supposed to, auto-increment the value of said field (more information about AUTO_INCREMENT can be found in the CREATE TABLE [mysql.com] pages of the manual). I left an echo statement in there if you would like to uncomment it and comment out the mysql_query first to see how it is going to work.

Note: You'll only want to run this once or you will create duplicate phone number entries in your table. Yes, they would have a unique

id
key, but duplicate phone numbers nevertheless.

BitBanger

1:44 pm on Jan 23, 2004 (gmt 0)

10+ Year Member



I assume you have connected to and selected the database?

If so, then replace the 'echo' statement with something like this:


$content = trim($content); /* trim() removes trailing whitespace */
$query = "INSERT INTO `friendstel` (tel) VALUES ({$content})";
mysql_query($query) or die("I can not insert into the table because: " . mysql_error());

Mitch888

6:54 pm on Jan 23, 2004 (gmt 0)

10+ Year Member



how come I never thought of that? I was approaching it all wrong. The solution is so simple. I will try it now. Thank you for the insight :)