/    Sign up×
Community /Pin to ProfileBookmark

Fatal error: Uncaught Error: Call to a member function query() on null

I know I have the error because of the scope in my method and the variable $conn is not defined there. How do I define that protected variable in my second class so I could make connection to my DB and fetch array.

[code] class Config{
private $host;
private $user;
private $pass;
private $db;
protected $conn;

// open connection to database
public function __construct() {
$this->db_connect();
}

static public function db_connect(){
$host = ”;
$user = ”;
$pass = ”;
$db = ”;

$conn = new mysqli($host, $user, $pass, $db);
if(mysqli_connect_errno()){
$msg = “Database connection failed: “;
$msg .= $conn->connect_error;
$msg .= ” (” . $conn->connect_errno . “)”;
exit($msg);
}
}
}[/code]

My second class

[code]class Database extends Config{

public function __construct(){
parent::__construct();
}

static public function find_by_sql($sql){
$result = $conn->query($sql);
if(!$result){
exit(“Database query failed.”);
}

//gather result into objects
$object_arr = [];
while($record = $result->fetch_assoc()){
$object_arr[] = htmlentities($record);
}
// result object method to free result set
$result->free();
}

}[/code]

now the use

[code]Database::db_connect();
$sql = “SELECT * FROM Events “;
$event = Database::find_by_sql($sql);

echo ‘<pre>’;
echo print_r($event);
echo ‘</pre>’;[/code]

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogSep 23.2018 — Looks like you need to save $conn as a class variable, instead, so that it can be referenced via $this-&gt;conn or self::$conn as applicable in other methods (depending on whether you make it static or not).
×

Success!

Help @marcellio spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...