0

我正在尝试移植在此页面mysql_...上找到的数据库备份脚本,因为它会引发已弃用的警告。

到目前为止,我的努力如下,但脚本向我抛出了几个我不知道如何解决的错误。我对 PHP 只是稍微熟悉,所以我很可能在这里犯了初学者的错误。

抛出的错误是:

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

第 109 行是(并标有 // * ** * ** *):

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

我一直在玩public/ protected(for initializeDatabase) 和global(for $db) 关键字,但我不确定这是原因还是我做错了。

谁能很容易地发现我在这里做错了什么?


<?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;
    }
}
4

3 回答 3

1

你需要 $db 作为全局,检查这个链接有更多的解释: http: //php.net/manual/en/language.variables.scope.php

于 2013-08-11T09:50:44.927 回答
1

添加属性

/**
 * Connection variable
 */

 var $db = ''

并将所有替换$db$this->db

例子 :

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

$this->db = new PDO("mysql:host=$this->host;dbname=$this->dbName;charset=$this->charset", $this->username, $this->passwd );
于 2013-08-11T09:51:46.720 回答
1

您的 $db 变量在方法 initializeDatabase() 中是本地的,并且仅在此方法中可用。

你可以有一个私有属性 $db,并在整个班级中调用 $this->db 而不是 $db。

于 2013-08-11T09:47:29.600 回答