StuBlackett
StuBlackett

Reputation: 3855

Writing a Database Query to a file

I am trying to write a Database Query to a file, But am just wondering how I get the SQL Data to be input into the file.

It is currently outputting nothing to the .txt file at all. I suspect its something to do with the while loop and am questioning whether it needs to be there or not.

My code is :

function backup_tables($host,$user,$pass,$name,$tables = '*')
{

$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);

$query = "SELECT gamename, username, MAX(thescore)
          FROM game_scores
          GROUP BY gamename, username
          ORDER BY gamename, thescore DESC";

$result = mysql_query($query);

while($row = mysql_fetch_array($result)) {
    $scoredata = $row;
}


//save file
$handle = fopen('scores/games-backup'.'.txt','w+');
fwrite($handle,$scoredate);
fclose($handle);

echo "Success";
 }

Any help on writing the SQL Results to this text file would be much appreciated.

Upvotes: 1

Views: 3791

Answers (4)

472084
472084

Reputation: 17894

$row is an array, you will need to make it a string before you can write it to a file, you can use implode().

$scoredata is also being overwritten in each loop, maybe use $scoredata[] instead

while($row = mysql_fetch_array($result)) {
    $scoredata[] = implode("; ", $row);
}

This will make $scoredata an array also, so you will need to convert that to a string too!

$handle = fopen('scores/games-backup'.'.txt','w+');
fwrite($handle,implode("\r\n", $scoredata));
fclose($handle);

This should print each database row on a new line in the file.

EDIT: This will just be a text file, formatted as text, not that great for a backup file. You will need to structure the text into an SQL format to make it useful..

Upvotes: 2

MartijnG
MartijnG

Reputation: 825

$row is not a string, you have to make it a string before you can put it into a file. And you have to change $scoredata to $scoredata[] because, it is now being overwritten continiously.

Upvotes: 2

ahmetunal
ahmetunal

Reputation: 3960

You can use print_r function with second parameter set true.

$str = print_r($row, true);    
fwrite($handle,implode("\r\n", $str));

Or you can serialize the array

$str = serialize($row);
fwrite($handle,implode("\r\n", $str));

Upvotes: 1

Moen
Moen

Reputation: 36

Try something like :

$handle = fopen('scores/games-backup'.'.txt','w+');

while($row = mysql_fetch_array($result)) {
  fputs($handle, join(';', $row)."\n");
}

fclose($handle);

$row is an array, you must join it (or access the elements )

Upvotes: 2

Related Questions