How can one effectively handle database connections in PHP classes?
To effectively handle database connections in PHP classes, it is recommended to create a separate class specifically for managing database connections. This class can include methods for establishing connections, executing queries, and closing connections. By encapsulating database connection logic within a dedicated class, it helps to improve code organization, reusability, and maintainability.
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'example';
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 close() {
$this->conn->close();
}
}
// Example of using the Database class
$db = new Database();
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . "<br>";
}
$db->close();
Keywords
Related Questions
- How can PHP developers efficiently manage data mutations, such as adding new records and deleting existing ones in a database table?
- How can PHP developers avoid adding unnecessary effects or watermarks when dynamically adding text to images?
- What is the best method to retrieve and display the selected radio button value in PHP?