将PHP脚本从mysql _...移植到PDO

时间:2013-08-11 09:39:38

标签: php pdo

我正在尝试移植this page上找到的数据库备份脚本,因为它发出警告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行是(并标有// * ** * ** * ):< / p>

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

我一直在玩public / protected(针对initializeDatabase)和global(针对$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;
    }
}

3 个答案:

答案 0 :(得分:1)

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

你可以拥有一个私有属性$ db,并在你的全班中调用$ this-&gt; db而不是$ db。

答案 1 :(得分:1)

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

答案 2 :(得分: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 );