I keep on getting this error
Call to a member function prepare() on a non-object in ..on line 134.
database.php
require_once("connect.php");
class Database {
private $connect;
function one() {
$connectdb = $this->connect;
$forms = new Forms();
$forms->two();
}
}
forms.php
require_once("connect.php");
class Forms {
private $connect;
function two() {
$connectdb = $this->connect;
$construct = $connectdb->prepare("SELECT child.*, parent.name as pname, parent.information as pinformation
FROM strings child LEFT JOIN strings parent on child.pageid=parent.id WHERE child.sid=:id AND child.submittype='2'");
$executequery = $construct->execute(array(':id'=>$id));
}
}
The error happens on the line with the query. My guess is something to do with the private variable $connect
. How do I solve this?
you need to instantiate first a new object of the Class Database
and assign it to $connect
:
$this->connect = new Database();
and then you might use it:
$connectdb = $this->connect;
Connect in your Forms class is not a database connector.
class Forms {
private $connect;
public function __construct(){
$this->connect = Database::getConnection(); // we will define this method below
}
function two() {
$connectdb = $this->connect;
$construct = $connectdb->prepare("....query....");
$executequery = $construct->execute(array(':id'=>$id));
}
}
The database connector:
class Database {
private static $connect;
public static function getConnection(){
if (self::$connect){
return self:$connect;
}
self::$connect = new mysqli(...) or what ever connection u use
}
}