Search code examples
phpdatabaseclassmethodsconnection

Connecting to Database inside Class and method nothing happens?


I am trying to add my code I use to connect to my database to a class and method. When not inside class it echo connection successful. But with new code I don't get anything. No error or success? Should I even be putting this inside a class and using a method?

<?php

class DBconfig
{

    private $servername = "localhost";
    private $username = "*********";
    private $password = "***************";


    // public function __construct($servername,$username,$password)
    // {

    //     $this -> servername = $servername;
    //     $this -> username = $username;
    //     $this -> password = $password;
    // }


    public function dbConnect($servername,$username,$password)
    {

            // $servername = $this -> servername;
            // $username = $this -> username;
            // $password = $this -> password;

        try 
        {

            $conn = new PDO("mysql:host=$servername; dbname = training", $username, $password);
            // set the PDO error mode to exception
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo "Connected successfully";
        } 

            catch(PDOException $e) 
        {
            echo "Connection failed: " . $e->getMessage();

        }
        
    }
}


    
?>

AS you can see I have tried a couple of things that are commented out. These did not help.


Solution

  • Some changes added to the code below. it works fine

       class DBconfig
    {
    
    private $servername = "localhost";
    private $db = "**************";
    private $username = "**************";
    private $password = "**************";
    
    private $conn;
    
    public function __construct()
    {
        $this->dbConnect();
    }
    
    public function dbConnect()
    {
        try 
        {
            $this->conn = new PDO("mysql:host=$this->servername; dbname = $this->db", $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo "Connected successfully";
        } 
    
        catch(PDOException $e) 
        {
            echo "Connection failed: " . $e->getMessage();
        }
    }
    
    public function getConnection(){
        return $this->conn;
    }
    }
    
    $db = new DBconfig();
    $conn = $db->getConnection();