Could any one explain me how to create a text file using php where the records should be from mysql
2 Answers
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);
5 Comments
Fero
hi.. thanks nik. its working fine. But how to merge multiple records. thanks for the answer
Eiko
Or write the data directly (using multiple fwrite) to the file without concatenating in php if you have larger data sets.
nik
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
Fero
is it possible to create a table structure and store the data
nik
Then you need to create .csv file rather then txt file.
$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);
file_put_contents— Write a string to a file