How can classes be effectively utilized in large websites with database interactions?
Classes can be effectively utilized in large websites with database interactions by creating separate classes for database operations, such as connecting to the database, querying data, and updating records. This helps in organizing the code, improving readability, and promoting code reusability.
// Database class for handling database operations
class Database {
private $db_host = 'localhost';
private $db_user = 'username';
private $db_pass = 'password';
private $db_name = 'database';
private $conn;
public function __construct() {
$this->conn = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function escapeString($str) {
return $this->conn->real_escape_string($str);
}
public function close() {
$this->conn->close();
}
}