How can object-oriented programming principles be better applied to the database class in the code snippet?
The object-oriented programming principles can be better applied to the database class by encapsulating the database connection details within the class, using private properties for the connection details, and creating methods within the class to interact with the database. This will make the database class more modular, reusable, and easier to maintain.
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'my_database';
private $conn;
public function __construct() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function fetch($result) {
return $result->fetch_assoc();
}
public function close() {
$this->conn->close();
}
}
// Example usage
$db = new Database();
$result = $db->query("SELECT * FROM users");
while($row = $db->fetch($result)) {
echo $row['username'] . "<br>";
}
$db->close();
Related Questions
- What are some common security risks associated with poorly coded PHP scripts like the one mentioned in the forum thread?
- Are there any specific forums or communities that are recommended for PHP developers?
- What are the potential benefits of using a Root-Server for handling email sending in PHP applications?