I figure out how to write all the entries from my database onto a text file.

header("Content-Type: text/plain");
header("Content-Disposition: Attachment; filename=test.txt");
header("Pragma: no-cache");
exit;

How do I modify the text file??
Each entries (or row) have 5 elements in it and there are multiple entries in my database.
How do I write each elements follow by a comma onto a text file? Each row in the database would have a new line in my text file as well.

tks

I use fwrite to write onto a text file
But how do I know that I'm done with each entries when I'm writing to a text file, so I can separte them with a comma because each entries can have more then one word in it

SQL Entries:
Name | Age | Country
John Adam Smith | 37 | USA
Steve Jones | 22 | Canada
Marie Eve Thomas Faucher | 19 | Canada

Also, how do I know when I reach the end of the row, so I can add in a new line.

PHP has built in functions to handle this case. They are called fgetcsv and fputcsv.

You can read the textfile into an array using fgetcsv and write the changed values back using fputcsv. These functions handles both the field delimiter (comma or semi-colon), string enclosures (the " or ') and the escape character (the backslash).

Nice samples are included in the php.net manual.

There are many ways to acheive this, but it's best if you work this out yourself (teach a man to fish.)

<?php
$arr = array();
//make data connection and send query
while ($row = mysql_fetch_assoc($res)){//loop through all db rows
    $arr[] = $row['Name'].", ".$row['Age'].", ".$row['Country']."\n"; 
    //store each line in the array called $arr.
    }
//open the file ready for writing
//now loop through and write each line to file.
foreach($arr as $k => $v){
    //write $v to file
}
//close the file.
?>
Member Avatar for LastMitch

@hiyatran

How do I modify the text file??
Each entries (or row) have 5 elements in it and there are multiple entries in my database.
How do I write each elements follow by a comma onto a text file? Each row in the database would have a new line in my text file as well.

You can try this

$i=0;
foreach(file("test.txt") as $key => $value) {
   if($tempfile=explode(",",$value)) {
     if(@mysql_query("UPDATE test_table SET ".$tempfile[1]."='".$tempfile[0]."';")) {
       $i++;
     }
   }
}
if($i==sizeof(file("test.txt")) echo "Writing.";
else echo "Try Again!";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.