I am new to php and what I am trying to do is get $conn variable outside of the class.
I included this file from another file and tried to get the variable using $dbConfig->conn
but it returns nothing.
This is the notice I got on the another page. Notice: Undefined variable: dbConfig in C:\xampp\htdocs\Chat\login.php on line 8
<?php
class dbConfig {
public $host;
public $username;
public $password;
public $dab;
public $conn;
public function dbConnect() {
$conn = mysqli_connect($this->host,$this->username,$this->password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully to server";
}
$db_selected = mysqli_select_db($conn, $this->dab);
if (!$db_selected) {
// if the given database doesn't exists
// creates new database with that name
$db_sql = 'CREATE DATABASE chatapp';
// verify the database is created
if (mysqli_query($conn, $db_sql)){
echo "Database chatapp already exists or created successfully
";
} else {
echo 'Error creating database: ' . mysqli_error() . "
";
}
}
// creating tables
$table_sql = "CREATE TABLE IF NOT EXISTS users (".
"uid INT PRIMARY KEY AUTO_INCREMENT,".
"username VARCHAR(30) UNIQUE,".
"password VARCHAR(50),".
"name VARCHAR(100),".
"email VARCHAR(70) UNIQUE); ";
// verify the table is created
if (mysqli_query($conn, $table_sql)) {
echo "Table: users already exists or created successfully
";
} else {
echo 'Error creating table: ' . mysqli_error($table_sql) . "
";
}
}
}
$obj = new dbConfig();
$obj->host = 'localhost';
$obj->username = 'root';
$obj->password = '';
$obj->dab = 'chatapp';
$obj->dbConnect();