Reputation: 1067
i have a table called users and a field on it called email
i want to retrieve (all) emails from this field ,then store them in a file
i tried to use while loop,and then i used file_put_contents,but this only save the first column and not the whole data
how can i store all emails retrieved from while loop in a file
$data=$db->query("select * from users order by userid desc");
while($row=$data->fetch_assoc()){
$string=$row['email'].",";
file_put_contents("data.txt",$string);
}
Upvotes: 1
Views: 2779
Reputation: 2864
I think, you want this:
file_put_contents("data.txt", $string, FILE_APPEND);
see http://php.net/manual/en/function.file-put-contents.php
Upvotes: 1
Reputation: 7918
You can use the MySQL inbuilt function to export the data to the file
SELECT * FROM `table_name` INTO OUTFILE /path/file.txt
and if you want to import then do like this
LOAD DATA INFILE '/path/file.txt' INTO TABLE db2.my_table;
Upvotes: 2
Reputation: 11378
I think it's better to move file_put_contents()
out of the while loop and only call it once when you have collected all the data into a string.
Try this:
$data=$db->query("select * from users order by userid desc");
$string="";
while($row=$data->fetch_assoc()){
$string .= $row['email'].",";
}
file_put_contents("data.txt",$string);
ps:
If you are appending data to a file (in general), you should use
file_put_contents("data.txt",$string,FILE_APPEND);
http://php.net/manual/en/function.file-put-contents.php
Upvotes: 2
Reputation: 13495
You'd probably be better off with...
$data = $db->query("select * from users order by userid desc");
$emails = array();
while ($row = $data->fetch_assoc()) {
$emails[] = $row['email'];
}
file_put_contents("data.txt", implode(', ', $emails));
Upvotes: 1