How can object-oriented PHP be utilized to handle database query results and variable assignment effectively?
When handling database query results and variable assignment in PHP, object-oriented programming can be utilized effectively by creating classes to represent database connections, query results, and data objects. By encapsulating database interactions within classes, code can be more organized, reusable, and easier to maintain.
// Example of utilizing object-oriented PHP for handling database query results and variable assignment
class DatabaseConnection {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
}
public function query($sql) {
return $this->connection->query($sql);
}
}
// Example usage
$db = new DatabaseConnection('localhost', 'username', 'password', 'database');
$result = $db->query('SELECT * FROM users');
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$user = new User($row['id'], $row['name']);
// Process $user object as needed
}
}