0

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!

1 Answer 1

2

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());
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, that makes sense, thank you. Another quick question, but is it right that I set those variables to private, or should they simply be var?
Yes, private is the way to go. You want to make it so your class controls access to those variables.

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.