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
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".
}

Link to comment
Share on other sites

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);
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.