0

I set up the following code for my DB-Connection, however I cannot create a connection to my database from another .php file (in another directory):

My database.php file:

<?php

    ini_set('display_errors', 'On');

    public class Database {

        public function __construct() {
            $this->dsn = 'mysql:host=xxx;dbname=xxx';
            $this->username = 'xxx';
            $this->password = 'xxx';   
        }

        public function __construct($dsn, $username, $password) {
            $this->dsn = $dsn;
            $this->username = $username;
            $this->password = $password;
        }

        public function db_connect() {
            try {
                $database = new PDO($this->dsn , $this->username, $this->password);
                return $database;
            } catch(PDOException $e) {
                echo $e->getMessage();
            }
        }

        public function run_query($database, $query){            
            try {
                $result = $database->prepare($query);
                $result->execute();
                return $result;
            } catch (Exception $e) {
                echo $e->getMessage();
                die();
            }
        }

    }

?>

The directory of this file is currentdirectory/php/database.php.

I am trying to instantiate a Database connection in another file (named page.php) with the following code:

include("php/database.php")
$database = new Database();
$connection = $database->db_connect();
$result = $database->run_query($connection, $query);

The directory of this file is currentdirectory/page.php.

I have been searching for an error quite a while now and cannot see what I did wrong. The other questions regarding PDO-DB classes didn't help me much further either. Thanks in advance for any help!

4
  • 1
    What error did you get? Commented Dec 24, 2015 at 12:09
  • Technically don't create multiple constructors. Commented Dec 24, 2015 at 12:12
  • It didn't execute at all Commented Dec 24, 2015 at 12:12
  • @hardiksolanki I thought of that too, but it still doesn't execute after removing the one without params. Commented Dec 24, 2015 at 12:22

2 Answers 2

3

public, private, protected are used for Class methods and/or properties not for Classes themselves.
You shouldn't have 2 constructors, or two functions with the same name, you will get a fatal error, 'cannot redeclare ..'

See the example below.
It uses private properties for the dsn components, the pdo object itself and the pdo statement.
You can return these in the methods themselves so you can chain them.

<?php

class Database {

    private $host;
    private $username;
    private $password;
    private $database;

    private $pdo;
    private $stmt;


    public function __construct($host,$user,$pass,$db) {
        $this->host = $host;
        $this->username = $user;
        $this->password = $pass;
        $this->database = $db;

        $dsn = 'mysql:dbname=' . $this->database .';host=' . $this->host;

        try {

            $this->pdo = new PDO($dsn, $this->username, $this->password);

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

    }

    public function query($query){
        $this->stmt = $this->pdo->prepare($query);
        return $this;
    }

    public function getResults(){
        $this->stmt->execute();
        return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }

}

Usage

// include the file

$db = new Database('localhost','root','','db_name');

print_r($db->query('select * from my_table limit 10')->getResults());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Appreciate it!
Lovin' the well-explained ;-)
1

You need to do some changes in your database.php file, So your file code should be :

<?php

    ini_set('display_errors', 'On');

    class Database{

        public function __construct(){
            $this->dsn = 'mysql:host=xxx;dbname=xxx';
            $this->username = 'xxx';
            $this->password = 'xxx';
        }

        public function db_connect() {
            try {
                $database = new PDO($this->dsn , $this->username, $this->password);
                return $database;
            } catch(PDOException $e) {
                echo $e->getMessage();
            }
        }

        public function run_query($database, $query){            
            try {
                $result = $database->prepare($query);
                $result->execute();
                return $result;
            } catch (Exception $e) {
                echo $e->getMessage();
                die();
            }
        }

    }

?>

And you page.php file code should be:

include("php/database.php")
$database = new Database();
$connection = $database->db_connect();
$query = "SELECT * FROM table";
$result = $database->run_query($connection, $query);

public scope only for variable/function. It's not for Class.

Comments

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.