How can object-oriented principles be applied to handle database query results in PHP?
To handle database query results in PHP using object-oriented principles, you can create a class to represent a single row of data from the query result. This class can have properties that correspond to the columns in the query result, and methods to manipulate or display the data.
class QueryResult {
public $id;
public $name;
public $email;
public function __construct($id, $name, $email) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
}
public function displayInfo() {
echo "ID: " . $this->id . "<br>";
echo "Name: " . $this->name . "<br>";
echo "Email: " . $this->email . "<br>";
}
}
// Assuming $result is the database query result
while($row = $result->fetch_assoc()) {
$queryResult = new QueryResult($row['id'], $row['name'], $row['email']);
$queryResult->displayInfo();
}
Keywords
Related Questions
- What are the potential pitfalls of relying on visible line breaks in text input fields when retrieving and displaying the data in PHP?
- How can regular expressions be used effectively in PHP to achieve the desired result?
- Are there any potential issues with using substr_count() to count the frequency of a word in PHP?