As has been suggested, I am trying to use the connection injection technique to allow my main class to operate. The injection code is from a class on another file. See fig A from connection.php
class qcon{
public static $conn;
function dbcon()
{
if (empty($conn))
{
$host = 'x';
$username = 'x';
$password = 'x';
$dbname = 'x';
$conn = mysqli_connect($host , $username , $password ,$dbname) or die("Oops! Please check SQL connection settings");
}
return $conn;
}
}
Here, I have my class injection code that is a method within my main class. See class.php on fig B
class dbcats {
var $conn;
public function __construct(qcon $dbcon)
{
$this->conn = $dbcon;
}
function getResult(){
$result = mysqli_query($this->conn , "SELECT * from member" ); // Error see end of question
if ($result) {
return $result;
}
else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
}
And finally, see fig C for the call I make within the webpage.
$db1 = new qcon();
$db1->dbcon();
$helper = new dbevent($db1);
$result = $helper->getResult();
The above is causing the following
Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\xxxxxxxxxxxxxx\webpage.php on line 35
Would someone kindly be able to look at what I have done and point out specifically what I'm doing wrong, and how to correct the scripts to get them to operate.
You don't take care of the returned $conn
.
$db1 = new qcon();
$db1->dbcon();//This line returns the connection
$helper = new dbevent($db1);
$result = $helper->getResult();
It should be like this.
$db1 = new qcon();
$conn = $db1->dbcon();
$helper = new dbevent($conn);
$result = $helper->getResult();
You have a lot of problems in your code, here is the revised code( please find the difference yourself)
class Qcon
{
public static $conn;
public static function connection()
{
if (empty(self::$conn)) {
$host = 'x';
$username = 'x';
$password = 'x';
$dbname = 'x';
self::$conn = mysqli_connect($host, $username, $password, $dbname) or die("Oops! Please check SQL connection settings");
}
return self::$conn;
}
}
And then:
$helper = new dbevent(Qcon::connection());
$result = $helper->getResult();