inserting usernames from a .txt into mysql

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
CBaZ
Forum Newbie
Posts: 1
Joined: Wed Jul 02, 2008 2:45 pm

inserting usernames from a .txt into mysql

Post by CBaZ »

I am not sure how to create the loop so that it adds each username in a seperate row. in the text file it stores usernames as such
user1
user2
this is coming from an IRC bot therefore I need to use the .txt file ;)

Code: Select all

 
<?php error_reporting(E_ALL) ; ini_set('display_errors','1'); ?>
<?php 
error_reporting(E_ALL); 
$connect = mysql_connect("localhost", "user", "pw") or die ("Could not connect to database: " . mysql_error()); mysql_select_db("db", $connect) or die ("Could not select database");  
$query = mysql_query("SELECT * FROM users WHERE username != '" . $username . "'") or die("QUERY FAILED: " . mysql_error());   
$triv = file_get_contents("trivia/users_online2.txt"); 
$date = date("YmdHis");
echo " ".$triv.""; 
if (mysql_num_rows($query) >= 0) { 
for($i=0;$i<count($triv);$i++) {
   $result = "INSERT INTO users (username, created) values ('".$triv."', '".$date."')" ; 
}} else { 
   echo "number of rows: '".mysql_num_rows($query)."'<br>"; 
   exit; 
} 
$row2 = mysql_query($result) or die("QUERY FAILED: " . mysql_error()); 
$sql = mysql_query("SELECT * FROM users WHERE user_id != '$user_id' ORDER BY created");
 
 
?> 
 
 
kilermedia
Forum Newbie
Posts: 7
Joined: Wed Jul 02, 2008 11:00 pm
Location: California, USA

Re: inserting usernames from a .txt into mysql

Post by kilermedia »

The function file_get_contents is your enemy in this case right here as it uses more resources than this other method and also doesn't act appropriately. Here's a much more easier and elegant methodology of going about this:

Code: Select all

 
<?php
$date = date("YmdHis");
// I prefer fopen, fgetcsv, fclose ...in this case.
$handle = fopen('trivia/users_online2.txt', "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { /* the "," is in case you want to add any more fields, then you could do like: user1,"user name","userpass","etc" */
    $piece1 = $data[0];
    $queryExe = @mysql_query("INSERT INTO users (username, created) values ('$piece1', '$date');");
    echo ($queryExe) ? 'Success with '.$piece1.'!<br />' : 'Error. MySQL said: '.@mysql_error().'<br />'; 
}
fclose($handle);
?>
 
Of course, I left out all of the db setup and whatnot. But you should get the idea. ;)

Oh, and if you're wondering what's wrong with your original code...you should have went with a while loop and not a for.
Post Reply