0

Hey guys i have recently moved over to PDO and OOP and having some problems with the connection statement. The errors i am receiving are;

Notice: Undefined variable: db_host in C:\Users\PC\Documents\XAMPP\htdocs\libs\class.Manage.php on line 14

Fatal error: Cannot access empty property in C:\Users\PC\Documents\XAMPP\htdocs\libs\class.Manage.php on line 14

class ManageHits{

protected $link;
protected $db_host = "localhost";
protected $db_name = "ajaxrating";
protected $db_user = "userone";
protected $db_pass = "passwordone";

function __construct(){
    try{
    $this->link = new PDO($this->$db_host,$this->$db_name,$this->$db_user,$this->$db_pass);
        return $this->link;
    }
    catch(PDOException $e){
        return $e->getMessage;
    }
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

3 Answers3

0
  1. Read at least any tutorial on PDO.

  2. Connect to PDO proper way, creating a PDO instance.

  3. Pass that instance in your ManageHits class.

    class ManageHits{
    
        protected $link;
    
        function __construct($db){
            $this->link = $db;
        }
    }
    
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

You are incorrectly calling your objects inside of new PDO():

$this->$db_host

should be

$this->db_host // and so forth
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
0

You should read a step by step tutorial about PDO

Furthermore your code has many issues.

  1. $e->getMessage; => $e->getMessage();
  2. constructor should be public I assume ?
  3. your variables should be private
  4. constructors serve to instantiate the class
  5. PDO
  6. initialize your variables inside the constructor for compatibility

This is a working example assuming your connection info is correct:

class Con{

    protected $link;
    protected $db_host;
    protected $db_name;
    protected $db_user;
    protected $db_pass;

    public function __construct(){

        $this->db_host = "localhost";
        $this->db_name = "ajaxrating";
        $this->db_user = "userone";
        $this->db_pass = "passwordone";        

        try{

            $this->connection = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
            echo 'Connection established!';
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }
}

$db = new Con();
Community
  • 1
  • 1
0x_Anakin
  • 3,229
  • 5
  • 47
  • 86