I am learning php
oop with mysql
and I am having trouble fixing this code.
I have checked it twice and also checked this platform to confirm.
<?php require 'databasesclass.php'; $database = new Database(); $database->query('SELECT * FROM users'); $rows = $database->resultset(); print_r($rows);
and my data base class are
<?php class Database{ private $host = 'localhost:8889'; private $user = 'root'; private $pass = 'root'; private $dbname = 'register'; private $dbh; private $error; private $stmt; public function __construct(){ // Set the DSN $dsn = 'mysql:host='. $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass; // set options $options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); try { $this->dbh = new PDO($dsn, $this->user, $this->pass, $options); } catch (PDOException $e) { $this->error = $e->getMessage(); } } public function query($query){ $this->stmt = $this->dbh->prepare($query); } public function bind($pram, $value, $type = null){ if (is_null($type)){ switch(true) { case is_int($value): $type = PDO::PRAM_INT; break; case is_bool($value): $type = PDO::PRAM_BOOL; break; case is_null($value): $type = PDO::PRAM_NULL; break; default: $type = PDO::PRAM_STR; } } $this->stmt->bindValue($parm, $value, $type); } public function execute(){ return $this->stmt->execute(); } public function resultset(){ $this->execute(); return $this->stmt->fetchALL(PDO::FETCH_ASSOC); } }
Fatal error: Uncaught Error: Call to a member function prepare() on null in C:MAMPhtdocsPracticedatabasesclass.php:31 Stack trace: #0 C:MAMPhtdocsPracticeindex.php(7): Database->query(‘SELECT * FROM u…’) #1 {main} thrown in C:MAMPhtdocsPracticedatabasesclass.php on line 31
And the Line 31 is:
$this->stmt = $this->dbh->prepare($query);
Advertisement
Answer
No need to pass $this->user and $this->pass into your $dns variable. Remove them from there.
So $dns variable will be
from
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
to
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
Please check and let me if you see any error there.