I am new to using PHP in an OOP way but have found an issue with my database connection class.
I have a file with this mysqli connection class here
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpassword';
$db_host = 'localhost';
class database {
public $mysqli;
public function connect($db_host, $db_user, $db_password, $db_name){
$this->mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
if ($mysqli->connect_errno) {
return "Sorry Andre, but you seem to have messed up the DB connection :(";
}
}
}
$newConnection = new database;
$newConnection->connect($db_host, $db_user, $db_password, $db_name);
I then want to use the variable $mysqli in a db connection in another file - this is a simple insert to a database using $mysqli variable to connect. I included the above in the connection file but it seems the $mysqli variable is not being returned when I call the method within the database class. I get the PHP error saying...
Fatal error: Call to a member function prepare() on a non-object in...
I have seen that using
global $mysqli;
works however I want to do it the proper way as I have heard that is not good practice.
I understand that I am potentially doing things a bit wrong here as I'm new to using OOP but I assumed that by returning that variable in the connect function I can then access it from creating the class outside.
Help is appreciated, thanks.