I need help in understanding the right way to pass an object (MySQL connection) created in one method to another method within the same class.
I am trying to create a database class that loads the connection using a constructor and all other methods, use this connection to perform their respective functions.
While trying to do so I keep getting this error:
Fatal error: Call to a member function query() on a non-object in /database.php on line 44
My code:
class database
{
public $mysqli;
public function __construct($database_server, $database_name, $database_user, $database_pass)
{
$mysqli = new mysqli($database_server,$database_user, $database_pass, $database_name);
if ($mysqli->connect_error)
{
die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
}
echo "Database connection established successfully.<br>";
return $this->mysqli;
}
public function fetch_data()
{
$query = "select * from payment";
if ($result = $this->mysqli->query($query))
{
// fetch associative array
while ($row = $result->fetch_assoc())
{
printf ("%s (%s)\n", $row["id"], $row["status"]);
}
}
}
}
Any help would be appreciated. Thank you everyone.
Or
And
public $mysqli;will be better to beprotected.