Call to a member function query() on string OOP PHP -
i'm new oop php im trying learn doing few basic things, error im getting in title query keeps returning error.
<?php //connection starts here class connection{ private $host = 'localhost'; private $username = 'root'; private $password = ''; private $database = 'test'; public $conn; public function __construct(){ return $this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die("mysql error"); } } //users starts here class users{ public $db; public function __construct($db){ $this->db = $db; } public function getallusernames($db){ $query = "select * users"; //error on line $all_users = $this->db->query("$query"); while ($row = $all_users->fetch_assoc()) { return $row['username']; } } }
i have no idea im going wrong can me better understanding of ive done wrong, know have clean lot of previous code said im learning , that's story want know error means , what's making it..?
you're not far of actually. altered code bit , instantiated classes:
<?php //connection starts here class connection { private $host = 'localhost'; private $username = 'root'; private $password = ''; private $database = 'test'; private $conn; public function __construct(){ $this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die("mysql error"); } public function getconn(){ return $this->conn; } } //users starts here class users { private $db; public function __construct($db){ $this->db = $db; } public function getallusernames(){ $query = "select * users"; //error on line $all_users = $this->db->query("$query"); return $all_users; } } $connection = new connection(); $users = new users($connection->getconn()); $allusers = $users->getallusernames(); while ($row = $allusers->fetch_assoc()) { echo $row['username']; }
Comments
Post a Comment