Posted 2004-11-18T17:24:00+01:00 in php

Dump MySQL database table from PHP

Here's some boilerplate code for dumping a MySQL database table to file and reading it back in again.

select-star.php


        
<?php
    
# Command line PHP tool to backup my database tables to file.
    # Requirements:
    # - Does not require admin permissions.
    # - Simple structured data format that can be used programmatically.
    
set_magic_quotes_runtime(0);
    
$conn = @mysql_connect( 'localhost', '****', '****')
                or die(
'Cannot connect to database.');
    
mysql_select_db('****', $conn) or die(mysql_error($conn));
    
$get = 'SELECT * FROM `BooksReviews` ORDER BY last_modified';
    
$result = @mysql_query($get, $conn) or die(mysql_error($conn));
    while (
$row = mysql_fetch_assoc($result)) {
        
printf("%s\n", base64_encode(serialize($row)));
    }
    exit(
0);
?>

decode.php


        
<?php
    set_magic_quotes_runtime
(0);
    
$f = @fopen('php://stdin', 'r') or die('Missing stdin');
    while (
$line = fgets($f)) {
        
$ar = unserialize(base64_decode($line));
        
var_dump($ar); // TODO do something useful here.
    
}
    exit(
0);
?>

The first script dumps the table to standard output, so that you can redirect that to a file. The second script reads that dump from standard input. In a shell, you can test it like this for example:

$ ./select-star.php | ./decode.php