What are the potential issues when converting a query from procedural PHP to OOP PHP?
One potential issue when converting a query from procedural PHP to OOP PHP is maintaining proper encapsulation and separation of concerns. To solve this, you can create a separate class specifically for handling database queries, ensuring that your code follows the principles of object-oriented programming.
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);
}
public function close() {
$this->connection->close();
}
}
// Example usage
$database = new Database('localhost', 'username', 'password', 'database');
$result = $database->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
// Process each row
}
$database->close();
Related Questions
- What are some common pitfalls when handling values in PHP forms, such as dealing with spaces in variables?
- What are the possible drawbacks or limitations of using JavaScript to interact with a PHP script for tracking website visitors?
- What are some potential pitfalls when calculating and distributing a voucher amount across multiple items in PHP?