Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php variables not storing

Tags:

php

mysql

mysqli

I am trying to create a db class with php that takes the host ect as variable. I cant get the initialized values to stick and i am not sure why. When i initialize them at the top where i set them to public it works fine, but when i try to initialize them in the constructor it is not working.

    class Database {

    public $dbHost;
    public $dbUser;
    public $dbPass;
    public $dbName;

    public $db;

    public function __construct($Host, $User, $Pass, $Name){ 
        $dbHost = $Host;
        $dbUser = $User;
        $dbPass = $Pass;
        $dbName = $Name;
        $this->dbConnect();
    }

    public function dbConnect(){
        echo $dbPass;
        $this->db = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName);

        /* check connection */
        if (mysqli_connect_errno()){
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }else{
            //echo 'connection made';
        }
    }
like image 333
Troy Cosentino Avatar asked Dec 06 '25 09:12

Troy Cosentino


1 Answers

You're not initializing them properly in the constructor; try:

$this->dbHost = $Host;

What you're currently doing is initializing a local variable called $dbHost, whose scope is just the constructor function itself.

like image 102
andrewsi Avatar answered Dec 08 '25 23:12

andrewsi