0

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);
    }
}
  • 3
    For the hundredth time: **[Please, don't use `mysql_*` functions in new code](http://bit.ly/phpmsql)**. They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the **[red box](http://j.mp/Te9zIL)**? Learn about prepared *[statements instead](http://j.mp/T9hLWi)*, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this](http://j.mp/QEx8IB) article will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – Siguza Jul 24 '15 at 20:23

1 Answers1

0

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();.

War10ck
  • 12,387
  • 7
  • 41
  • 54
  • Here is the PDO version of the @War10ck solution. class Konektor { private $dbdsn = 'mysql:host=localhost;dbname=dbname'; private $dbuser = 'user'; private $dbpass = 'pass'; function testcon() { $this->dbh = new PDO($this->dbdsn, $this->dbuser, $this->dbpass); if (!$this->dbh) { echo 'Could not connect!'; } else { echo 'Connected'; } } } –  Jul 24 '15 at 20:53