Is it advisable to create a wrapper class for MySQLi in PHP, or is extending the built-in class a better approach?
Creating a wrapper class for MySQLi in PHP can provide a more organized and structured way to interact with the database, allowing for easier maintenance and scalability. On the other hand, extending the built-in MySQLi class can lead to tighter integration with the existing functionality but may limit flexibility in the long run. Ultimately, the decision depends on the specific requirements and preferences of the project.
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
return $this->connection->query($sql);
}
// Add more methods as needed for CRUD operations, transactions, etc.
}
// Example of using the Database wrapper class
$db = new Database('localhost', 'username', 'password', 'database');
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo $row['username'] . "<br>";
}