How does PHP handle database communication in object-oriented programming?
In object-oriented programming, PHP can handle database communication by creating a class that represents a database connection and using methods within that class to interact with the database. This allows for better organization of code and separation of concerns.
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'my_database';
private $connection;
public function __construct() {
$this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
return $this->connection->query($sql);
}
public function close() {
$this->connection->close();
}
}
// Example usage
$db = new Database();
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo $row['username'] . "<br>";
}
$db->close();