Jump to content

[SOLVED]save sql query to text file


mediabob

Recommended Posts

Hi, I am trying to query a db table and save the results to a tab delimited text file, but I can't seem to figure out how to do it  ???

can anyone help me with this it should be saved to a folder on the server and be formatted like

head    head    head
row      row      row

 

sort of like a spreadsheet

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/93959-solvedsave-sql-query-to-text-file/
Share on other sites

OK I tried that and get error

 

Parse error: syntax error, unexpected T_WHILE in ***/test.php on line 10

 

Here is my code I tried

 

$result = mysql_query("SELECT * FROM mydb",$db);

  
  $csvcontent = 'field1'."\t".'field2'."\t".'field3'."\n\r".
while ($row = mysql_fetch_array($result)) {
  $csvcontent .= $row['field1']."\t".$row['field2']."\t".$row['field3']."\n\r".
}

try

<?php
include 'db.php';

$sql = "SELECT * FROM tablename";
$res = mysql_query($sql) or die (mysql_error()."<p>$sql</p>");

$fp = fopen ('aaa.csv', 'w');

$row = mysql_fetch_assoc($res);
$heads = array_keys($row);
fputcsv($fp, $heads, ',', '"');              // write headings
do {
    fputcsv($fp, $row, ',', '"');                       // write data
} while ($row = mysql_fetch_assoc($res));
fclose ($fp);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.