In the context of the forum thread, what role does OOP principles play in resolving the reported error related to the DB class?
The reported error related to the DB class is likely due to the violation of OOP principles, specifically encapsulation. To resolve this issue, we can encapsulate the database connection within the DB class and ensure that all database operations are performed within the class methods.
class DB {
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
$db = new DB('localhost', 'username', 'password', 'database');
$result = $db->query('SELECT * FROM table');
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
$db->close();
Related Questions
- What are best practices for retrieving data from a database and displaying it in a textarea field in PHP?
- How can PHP developers ensure that pagination functionality works correctly when navigating through multiple pages of query results?
- What is the purpose of preg_match in PHP and how does it work?