SQLize Online / PHPize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
< ?php class Database { private $servername = "localhost"; private $username = "root"; // Change this to your MySQL username private $password = ""; // Change this to your MySQL password private $dbname = "sakila"; protected $conn; public function __construct() { $this->connect(); } private function connect() { $this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname); if ($this->conn->connect_error) { die("Connection failed: " . $this->conn->connect_error); } } public function getConnection() { return $this->conn; } public function __destruct() { $this->conn->close(); } } class Actor { private $db; public function __construct(Database $db) { $this->db = $db; } public function fetchAllActors() { $conn = $this->db->getConnection(); $sql = "SELECT actor_id, first_name, last_name FROM actor"; $result = $conn->query($sql); if ($result->num_rows > 0) { return $result->fetch_all(MYSQLI_ASSOC); } else { return []; } } } // Usage $db = new Database(); $actorModel = new Actor($db); $actors = $actorModel->fetchAllActors(); ? > < !DOCTYPE html > < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title > Actors List</title > < style > table { width: 50%; border-collapse: collapse; margin: 20px 0; } table, th, td { border: 1px solid black; } th, td { padding: 10px; text-align: left; } </style > </head > < body > < h1 > Actors List</h1 > < ?php if (!empty($actors)): ? > < table > < tr > < th > ID</th > < th > First Name</th > < th > Last Name</th > </tr > < ?php foreach ($actors as $actor): ? > < tr > < td><?php echo htmlspecialchars($actor['actor_id']); ?></td > < td><?php echo htmlspecialchars($actor['first_name']); ?></td > < td><?php echo htmlspecialchars($actor['last_name']); ?></td > </tr > < ?php endforeach; ? > </table > < ?php else : ? > < p > No actors found.</p > < ?php endif; ? > </body > </html >

Stuck with a problem? Got Error? Ask ChatGPT!

Copy Clear