3

Could any one explain me how to create a text file using php where the records should be from mysql

4

2 Answers 2

6

1) open a file in write mode:

   $myFile = "testFile.txt";
   $fo = fopen($myFile, 'w') or die("can't open file");

2) Write mysql query and fetch its data

   $data_query=mysql_query("SELECT name,age from table");
   while($data=mysql_fetch_array($data_query))
   $stringData.="Name: ".$data['name']." Age:".$data['age']."\n";

3) Write data into the file

   fwrite($fo, $stringData);

4) Close file

   fclose($fo);
Sign up to request clarification or add additional context in comments.

5 Comments

hi.. thanks nik. its working fine. But how to merge multiple records. thanks for the answer
Or write the data directly (using multiple fwrite) to the file without concatenating in php if you have larger data sets.
It depends on your data, check my edit done for the data of user's name and age, the .(dot) after $stringData will append multiple records Also the point made by Eiko is correct, its just the way you like to write your code
is it possible to create a table structure and store the data
Then you need to create .csv file rather then txt file.
0
$fh   = fopen('games_set_88.php',"w");//php path

$extend_q  = mysql_query('SELECT * from mod_games_set');

$row_count = mysql_num_rows($extend_q);

$col_count = mysql_num_rows(mysql_query('describe mod_games_set'));

$data_str  = "<?php \n"."    $"."mod_extend_type = array(\n";

$startout  = 1;

while($row=mysql_fetch_assoc($extend_q)){
$startin = 1;
foreach($row as $key =>$value){
if( $startin<$col_count){
    if($startin == 1){
        $data_str .= "      '".$value."'=>array('".$key."'=>'".$value."',";
         }else{
            if($startin < $col_count-1) 
                $data_str .= "'".$key."'=>'".$value."',";
            else 
               $data_str .= "'".$key."'=>'".$value."')";
            }
        $startin++;
    }
}

if($startout < $row_count) $data_str .= ",";
    $data_str .= "\n";
    $startout++;
}
$data_str .=" );\n?>";
fwrite($fh,$data_str);
fclose($fh);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.