Search code examples
phpmysqlclassprivate

PHP pass values from php file to other class


I am using a config.php file for a simular something, im trying to put my mysql credentials in there to then use them in a different file, but it does not pass the values,

is there any1 that could help me find a solution.

code config.php:

/* Database credentials*/
$dbHost = 'localhost';
$dbName = 'xx';
$dbUsername = 'xx';
$dbWachtwoord = 'xx'; 

code dbconnect.php:

<?php include 'config.php';
class Database
{
    private $host;
    private $db_name;
    private $username;
    private $password;
    public $conn;

    public function dbConnection()
    {
        $this->host = $dbHost;
        $this->db_name = $dbName;
        $this->username = $dbUsername;
        $this->password = $dbWachtwoord;
        $this->conn = null;
        try
        {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $exception)
        {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}

Class.user dbconnection:

<?php
require_once('config.php');
require_once('dbconnect.php');

class USER
{   

    private $conn;

    public function __construct()
    {
        $database = new Database();
        $db = $database->dbConnection();
        $this->conn = $db;
    }

    public function runQuery($sql)
    {
        $stmt = $this->conn->prepare($sql);
        return $stmt;
    }

Thanks in advance =)


Solution

  • Include 'config.php inside your class

     public function dbConnection()
        {
            include 'config.php';
            $this->host = $dbHost;
            $this->db_name = $dbName;
            $this->username = $dbUsername;
            $this->password = $dbWachtwoord;
            $this->conn = null;
            try
            {