Question

I have mysql database with users that contains their email, icq, skype, etc. and text file that contains some of the email address from database on each line. What I want to do is copy entire row from database of every user that is in the text file from one table to another.

Here is my code:

$filename="123.txt";
$fp = @fopen($filename, 'r'); 
$array = explode("\n", fread($fp, filesize($filename)));

$id = 1;
while($id <= 500){
$user = $array[$id];
$copy = mysql_query("INSERT INTO newusers SELECT * FROM oldusers WHERE email='$user'");
echo "$user<br>";
$id++;
}

But it insert nothing into new table. But when I use code like

mysql_query("INSERT INTO newusers SELECT * FROM oldusers WHERE email='emailofuser@gmail.com'"); 

It works just fine. How I should manage my code so it will read data from text and use it in SQL?

Was it helpful?

Solution 2

I got this working with code:

$filename="123.txt";   
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
$ex = preg_split('/\s+/', $contents);
foreach ($ex as $user) {   
  echo "$user";
  mysql_query("INSERT INTO newusers SELECT * FROM oldusers WHERE email='{$user}'");
  }    
fclose($handle);

Problem was that after reading text file line by line I was getting a space after every email so output was like:

some@thing.com any@thing.com goo@gle.net etc.

And because of this space after every email SQL though emails were different. But with calling preg_split() I removed spaces and everything is working. I hope I wrote it understandable.

OTHER TIPS

Instead of while you could use foreach.

foreach ($array as $user) {
  mysql_query("INSERT INTO newusers SELECT * FROM oldusers WHERE email='{$user}'");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top