What is the purpose of using a separate class for database connection in PHP applications?
Using a separate class for database connection in PHP applications helps to encapsulate the database-related functionality, making the code more organized and maintainable. It also allows for easier reuse of the database connection code across multiple parts of the application. Additionally, using a separate class makes it easier to switch between different database systems or configurations in the future.
class DatabaseConnection {
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 getConnection() {
return $this->connection;
}
}
// To use the database connection in your PHP application
$databaseConnection = new DatabaseConnection();
$connection = $databaseConnection->getConnection();
Related Questions
- How can session timeouts be effectively implemented to handle browser closures in PHP applications?
- In the provided PHP code, what could be a more efficient way to handle individual account balances instead of updating all accounts with the same value?
- What are the differences between concatenating strings in PHP using implode() and using a loop?