0

I am trying to port the database backup script found on this page because it is throwing a warning that mysql_... is deprecated.

My efforts so far are below, but the script is throwing couple errors at me that I just don't know how to solve. I'm only slightly familiar with PHP, so it is quite possible that I'm making a beginner's mistake here.

The error thrown is:

Notice: Undefined variable: db in ......../index.php on line 109 Fatal error: Call to a member function query() on a non-object in ......../index.php on line 109

Line 109 is (and marked with // *******):

foreach( $db->query('SHOW TABLES') as $row )

I've been playing around with public/protected (for initializeDatabase) and global (for $db) keywords, but I'm not sure if that is the cause or if I'm doing it wrong.

Can anyone easily spot what I'm doing wrong here?


<?php
/**
 * This file contains the Backup_Database class wich performs
 * a partial or complete backup of any given MySQL database
 * @author Daniel López Azaña <http://www.daniloaz.com>
 * @version 1.0
 */

/**
 * Changes by jippie:
 * ereg_replace("\n","\\n",$row[$j]); => preg_replace( '/\n/ , "\\n" , $row[$j] );
 * mysql_... => PDO
 */

// Report all errors
error_reporting(E_ALL);

/**
 * Define database parameters here
 */
define("DB_USER", 'username');
define("DB_PASSWORD", 'password');
define("DB_NAME", 'database');
define("DB_HOST", 'localhost');
define("OUTPUT_DIR", 'cache');
define("TABLES", '*');

/**
 * Instantiate Backup_Database and perform backup
 */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "<br /><br /><br />Backup result: ".$status;

/**
 * The Backup_Database class
 */
class Backup_Database {
    /**
     * Host where database is located
     */
    var $host = '';

    /**
     * Username used to connect to database
     */
    var $username = '';

    /**
     * Password used to connect to database
     */
    var $passwd = '';

    /**
     * Database to backup
     */
    var $dbName = '';

    /**
     * Database charset
     */
    var $charset = '';

    /**
     * Constructor initializes database
     */
    function Backup_Database($host, $username, $passwd, $dbName, $charset = 'utf8')
    {
        $this->host     = $host;
        $this->username = $username;
        $this->passwd   = $passwd;
        $this->dbName   = $dbName;
        $this->charset  = $charset;

        $this->initializeDatabase();
    }

    protected function initializeDatabase()
    {
        $db = new PDO("mysql:host=$this->host;dbname=$this->dbName;charset=$this->charset", $this->username, $this->passwd );
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/* JPH: mysql_... is deprecated
 *       $conn = mysql_connect($this->host, $this->username, $this->passwd);
 *       mysql_select_db($this->dbName, $conn);
 *       if (! mysql_set_charset ($this->charset, $conn))
 *       {
 *           mysql_query('SET NAMES '.$this->charset);
 *       }
 */
    }

    /**
     * Backup the whole database or just some tables
     * Use '*' for whole database or 'table1 table2 table3...'
     * @param string $tables
     */
    public function backupTables($tables = '*', $outputDir = '.')
    {
        try
        {
            /**
            * Tables to export
            */
            if($tables == '*')
            {
                $tables = array();
                // $result = mysql_query('SHOW TABLES');
                // while($row = mysql_fetch_row($result))
// *******
                foreach( $db->query('SHOW TABLES') as $row )
                {
                    $tables[] = $row[0];
                }
            }
            else
            {
                $tables = is_array($tables) ? $tables : explode(',',$tables);
            }

            $sql = 'CREATE DATABASE IF NOT EXISTS '.$this->dbName.";\n\n";
            $sql .= 'USE '.$this->dbName.";\n\n";

            /**
            * Iterate tables
            */
            foreach($tables as $table)
            {
                echo "Backing up ".$table." table...";

                // $result = mysql_query('SELECT * FROM '.$table);
                // $numFields = mysql_num_fields($result);
                $result = $db->query( 'SELECT * FROM ' . $table );
                $numFields = $result->columnCount();

                $sql .= 'DROP TABLE IF EXISTS '.$table.';';
                // $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
                $result2 = $db->query( 'SHOW CREATE TABLE ' . $table );
                $row2 = $result2->fetch();

                $sql.= "\n\n".$row2[1].";\n\n";

                for ($i = 0; $i < $numFields; $i++)
                {
                    // while($row = mysql_fetch_row($result))
                    while( $row = $result2->fetch() )
                    {
                        $sql .= 'INSERT INTO '.$table.' VALUES(';
                        for($j=0; $j<$numFields; $j++)
                        {
                            $row[$j] = addslashes($row[$j]);
                            $row[$j] = preg_replace( '/\n/' , "\\n" , $row[$j] );
                            if (isset($row[$j]))
                            {
                                $sql .= '"'.$row[$j].'"' ;
                            }
                            else
                            {
                                $sql.= '""';
                            }

                            if ($j < ($numFields-1))
                            {
                                $sql .= ',';
                            }
                        }

                        $sql.= ");\n";
                    }
                }

                $sql.="\n\n\n";

                echo " OK" . "<br />";
            }
        }
        catch (Exception $e)
        {
            var_dump($e->getMessage());
            return false;
        }

        return $this->saveFile($sql, $outputDir);
    }

    /**
     * Save SQL to file
     * @param string $sql
     */
    protected function saveFile(&$sql, $outputDir = '.')
    {
        if (!$sql) return false;

        try
        {
            $handle = fopen($outputDir.'/db-backup-'.$this->dbName.'-'.date("Ymd-His", time()).'.sql','w+');
            fwrite($handle, $sql);
            fclose($handle);
        }
        catch (Exception $e)
        {
            var_dump($e->getMessage());
            return false;
        }

        return true;
    }
}

3 Answers 3

1

add property

/**
 * Connection variable
 */

 var $db = ''

and replace all $db to $this->db

example :

$db = new PDO("mysql:host=$this->host;dbname=$this->dbName;charset=$this->charset", $this->username, $this->passwd );

to

$this->db = new PDO("mysql:host=$this->host;dbname=$this->dbName;charset=$this->charset", $this->username, $this->passwd );
Sign up to request clarification or add additional context in comments.

1 Comment

making the definition of property for the class. You can private
1

Your $db variable is local in the method initializeDatabase() and only available in this method.

You could have a private attribute $db, and called $this->db instead of $db in your whole class.

2 Comments

yess that seems to work. Only the database dump is about 10 times smaller in size since my PDO efforts, so I have some troubleshooting to do.
FYI: The 'compression' issue turned out to be a type result vs result2 in while( $row = $result->fetch() )
1

you need to $db as global, check this link there is more explanation:http://php.net/manual/en/language.variables.scope.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.