无法使用PHP连接到MySQL数据库

时间:2012-03-02 03:32:32

标签: php

我有一个3档:

class.database.php
config.php
test.php

在class.database.php中我使用:

<?php
class Database {

    private $db_connect;
    function __construct($config) {
        $this->connect($config);
    }

    function connect($config) {
        $this->db_connect = @mysql_connect($config['hostname'], $config['dbuser'], $config['dbpass']) or die("Can't connect to mysql server");
        @mysql_select_db($config['dbname'], $this->db_connect) or die("Can't select database mysql server");
        $this->query('set names utf8'); 
    }

    function disconnect() {
        mysql_close($this->db_connect);
    }

}
?>

在config.php我使用:

<?php
include_once 'class.database.php'; 

$config['hostname'] = 'localhost';
$config['dbuser'] = 'root';
$config['dbpass'] = '';
$config['dbname'] = 'test';

$db = new Database($config); 
?>

和test.php我使用:

<?php
include 'config.php';
include 'class.database.php';

何时在wampserver中运行test.php,主机警报错误为Fatal error: Cannot redeclare class Database in class.database.php on line 2

如何解决?

1 个答案:

答案 0 :(得分:4)

include两次class.database.php文件,这会产生此错误。始终使用include_once,而不是include