Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hello everyone!

I recreated the script from chapter 11 about file compression exactly as it is in the book but it only backs up the first table from any database. Here's the code as it is in my IDE:

<!doctype html>
<html lang="en">
	<meta charset="utf-8">
	<title>Database Backup</title>
	<link rel="stylesheet" href="style.css">
<?php # Script 11.1 - db_backup.php
// Set the name of the database
$db_name = 'testlogin';
// Make sure that the backup directory exists
$dir = "backups/$db_name";
if (!is_dir($dir)) {
	if (!@mkdir($dir)) {
		die("<p>The backup directory--$dir--could not be created.</p></body></html>");
// Get the current time
$time = time();
// Connect to the database
$dbc = @mysqli_connect('localhost', 'root', 'pass', $db_name) OR die("<p>The database--$db_name--could not be backed up.</p></body></html>");
// Retreive the tables in this database
$r = mysqli_query($dbc, 'SHOW TABLES') OR trigger_error("Error: " . mysqli_error($dbc));
// Confirm that at least one record was returned and print a message. No need to back-up an empty database!
if (mysqli_num_rows($r) > 0) {
	echo "<p>Backing up database '$db_name'.</p>\n";
	// Create a loop that fetches each table name
	while (list($table) = mysqli_fetch_array($r, MYSQLI_NUM)) {
		# Retrieve all the records from this table
		$q = "SELECT * FROM $table";
		$r2 = mysqli_query($dbc, $q);
		// If the table contains some records, open the text file for writing
		if (mysqli_num_rows($r) > 0) {
			if ($fp = gzopen("$dir/{$table}_{$time}.sql.gz", 'w9')) {
				# Retrieve all of the table's data and write it to the file
				while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
					foreach ($row as $value) {
						$value = addslashes($value);
						gzwrite($fp, "'$value', ");
					gzwrite($fp, "\n");
				} // End of WHILE loop.
				// Close the file and print a message to the browser
				echo "<p>Table '$table' backed up.</p>";
			} else {
				echo "<p>The file--$dir/{$table}_{$time}.sql.gz--could not be opened for writing.</p>\n";
			} // End of gzopen() IF.
		} // End of mysqli_num_rows() IF.
	} // End of WHILE loop.
} else {
	echo "<p>The submitted database--$db_name--contains no tables.</p>\n";

I tried to print out the $table array and it contains only one element which is baffling since the given database has multiple tables.

The query runs fine, so it can't be the cause of the problem. I'm really out of clues here as to what is going wrong.

Any suggestions would be much appreciated! Thank you!

Edited by Deleter
Link to comment
Share on other sites

So could you confirm...

- Running the "SHOW TABLES" command directly on the database returns multiple records (i.e., multiple results)?

- The while loop is only executed once?

- Do echo mysqli_num_rows($r) to see how many rows are in the result. 

Link to comment
Share on other sites


  • Create New...