I hope someone can help me with my small problem but I cannot figure it out. What I want to achieve is having one database.php file that connects to the database each time I call it. And then I want to be able to grab results, insert results etc in other files, but without having to have a seperate connect to the database line in those files.
What I have right now, is my database connection class:
<?php
$db_host = 'localhost';
$db_user = 'dbusername';
$db_pass = 'dbpassword';
$db_name = 'dbname';
class database {
public $mysqli;
public function connect($db_host, $db_user, $db_pass, $db_name)
{
$this->mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($this->mysqli->connect_errno)
{
return "An error occured while connecting to the database";
}
}
}
?>
Now when I include this file and setup a connection like so:
$whatever = new database();
I want to be able to perform some database actions with some functions in other classes like so:
require_once("whatever.class.php");
$test = new myclass();
$update = $test->updataDatabase();
And in my "whatever.class.php" file I have the following function:
public function grabResult($table, $where, $field)
{
$result = 'SELECT * FROM '.$table.' WHERE '.$where.' = '.$field;
$query = $this->mysqli->query($result);
And whatever I try, I always get the following error:
Call to a member function query() on a non-object in /home/etc/public_html/whatever.class.php on line 5
Basically what my question is, I want to be able to use "$this->mysqli" in another class without having to set up the database connection again in that class. I just want to include the database.class.php file and then connect plus being able to use $this->mysqli.
From another page I found this:
$newConnection = new database;
$newConnection->connect($db_host, $db_user, $db_pass, $db_name);
$mysqli = $newConnection->mysqli;
But that didn't do the trick. Same as the following, did not work:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
public function __construct($mysqli)
{
$this->mysqli = $mysqli;
}
I have also tried extending the "myclass" from database, with no luck, I tried using "::parent", also without any luck. Any help is greatly appreciated since I been struggling with this for a few days now.