简体   繁体   中英

PHP: Database Connection Class - Won't Connect

I'm having trouble with my DatabaseConnection class. I cannot seem to get $dbUser or $dbName variables to work for this connection class. I currently have to manually put the values in with quotes. Is there something I am doing wrong?

class DatabaseConnection {
    private $dbHost = "localhost";
    private $dbUser = "root";
    private $dbPass = "";
    private $dbName = "test";

    function __construct() {
        $connection = mysql_connect($dbHost, "root", $dbPass)
            or die("Could not connect to the database:<br />" . mysql_error());
        mysql_select_db("test", $connection) 
            or die("Database error:<br />" . mysql_error());
    }
}

If you have suggestions for improving my current class, by all means, let me know!

Since this is a class, you have to access your class variables using $this->dbHost , $this->dbUser , etc instead of $dbHost , $dbUser . Php requires that you use $this->variableName for class variables.

EDIT:

Here's your code with the mysql_connect variables changed to access your class variables

class DatabaseConnection {
    private $dbHost = "localhost";
    private $dbUser = "root";
    private $dbPass = "";
    private $dbName = "test";

    function __construct() {
        $connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
            or die("Could not connect to the database:<br />" . mysql_error());
        mysql_select_db("test", $connection) 
            or die("Database error:<br />" . mysql_error());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM