Search code examples
phpmysqlclassmysql-connect

Sql connection refused for PHP class


If I use simple SQL-PHP connection to test if it can connect to DB like:

$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected';
mysql_close($link);

It works and connects witohut problems, but when I add it to a class it gives me an error Access denied for user 'root'@'localhost'. This is the class code:

class Konektor {
    private $dbhost = "localhost";
    private $dbuser = "user";
    private $dbpass = "pass";
    var $link;
    function testcon() {
        $link = mysql_connect($dbhost, $dbuser, $dbpass);
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
        echo 'Connected';
        closedb($link);
    }
    function closedb($link) {
        mysql_close($link);
    }
}

Solution

  • Within the class, you need to access the variables using the $this syntax. Modify your class in the following way:

    class Konektor {
        private $dbhost = "localhost";
        private $dbuser = "user";
        private $dbpass = "pass";
        private $link;
        function testcon() {
            $this->link = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
            if (!$this->link) {
                die('Could not connect: ' . mysql_error());
            }
            echo 'Connected';
            $this->closedb();
        }
    
        function closedb() {
            mysql_close($this->link);
        }
    }
    

    Classes operate a little differently in PHP than procedural functions and variables. Within a class, you'll want to use private, protected or public to define your class variables (properties) and functions (methods). To access the properties (or methods), you'll need to use the $this->{property name / method name} syntax. For methods, you'll still need to use the parenthesis at the end of the call like so: $this->closedb();.