php - Unable to fix: "Fatal error: Call to a member function prepare() on a non-object.." -
i'm getting error , have no idea how fix it... in beginning had additionally error (same line) "db" unknown, able fix using correct syntax "$this->db..."
fatal error: call member function prepare() on non-object in c:\xampp\htdocs\gaestebuch\guestbook1.php on line 17
line 17:
$stmt = $this->db->prepare($query);
the refered code following:
include_once("datenbank.php");
class guestbook {public $db; public function getentries(){ $result = false; $query = 'select * guestbook order id desc'; $stmt = $this->db->prepare($query); //error in line (17) $stmt->execute(); $stmt->bind_result($id, $name, $message, $time, $date, $ip); while($stmt->fetch()) { $result[] = array('message' => $message, 'name' => $name, 'id' => $id, 'date' => $date, 'time' => $time); } $stmt->close(); return $result; } }
the database-connection, included in beginning looks this:
$db = new mysqli('localhost', 'root', '', 'guestbook'); if (mysqli_connect_errno()) { printf("verbindung fehlgeschlagen: %s\n",mysqli_connect_error()); exit(); }
i hope can me fixing (hopefully easy peasy) error.
you have class:
class guestbook { public $db;
you never give $db
property value, when do
$this->db->prepare($query);
you're doing
null->prepare($query);
give $db
value in class constructor (or make sure it's passed class somehow, either way..) , you'll fine.
the
$db = new mysqli('localhost', 'root', '', 'guestbook');
in database connection has no relation $db
variable in class unless pass class or make database-initialization happen within class.
Comments
Post a Comment