In what scenarios is object-oriented programming (OOP) with new mysqli recommended over mysqli_connect in PHP?
Object-oriented programming (OOP) with the new mysqli is recommended over mysqli_connect in PHP when you need to work with multiple database connections or when you want to encapsulate database functionality into reusable classes. OOP allows for better organization, code reusability, and easier maintenance of the database-related code.
// Using OOP with new mysqli
class Database {
private $host = 'localhost';
private $user = 'username';
private $password = 'password';
private $database = 'dbname';
private $connection;
public function __construct() {
$this->connection = new mysqli($this->host, $this->user, $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
$database = new Database();
$result = $database->query("SELECT * FROM table_name");
while ($row = $result->fetch_assoc()) {
echo $row['column_name'] . '<br>';
}
$database->close();
Related Questions
- In PHP, what are some best practices for handling and summarizing data stored in arrays?
- In the context of PHP cookie management, what role does browser settings play in the recognition of cookies?
- What are some security measures that can be implemented in PHP to prevent fake files from being uploaded?