I'm getting another error with this code. It's:
Connected successfully Fatal error: Uncaught Error: Call to a member function query() on null in index5.php:29 Stack trace: #0 index5.php(44): User->getAllUsers() #1 index5.php(55): ViewUser->showAllUsers() #2 {main} thrown in index5.php on line 29
I'm trying to echo out data from my database table called "indeximg" but this code gives me the error above. I'm not sure how to fix this. This is my code:
<?php
class Database {
private $host = 'localhost';
private $db_name = 'photos';
private $username = 'root';
private $password = '';
private $conn;
protected function connect() {
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo 'Connection Error: ' . $e->getMessage();
}
$this->conn = null;
}
}
class User extends Database {
protected function getAllUsers() {
$sql = "SELECT * FROM indeximg";
$result = $this->connect()->query($sql);
$numRows = $result->num_rows;
if ($numRows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
}
}
class ViewUser extends User {
public function showAllUsers() {
$datas = $this->getAllUsers();
foreach ($datas as $data) {
echo $data['id']."<br>";
echo $data['username']."<br>";
}
}
}
$users = new ViewUser();
$users->showAllUsers();
?>