How can a PHP developer efficiently loop through the results of a database query using a custom class and handle single or multiple rows?
To efficiently loop through the results of a database query using a custom class and handle single or multiple rows, you can create a class that encapsulates the database connection and query execution logic. Within this class, you can have methods to fetch single or multiple rows from the query result and handle them accordingly.
class DatabaseHandler {
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 fetchSingleRow($result) {
return $result->fetch_assoc();
}
public function fetchMultipleRows($result) {
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
}
// Example of using the DatabaseHandler class
$db = new DatabaseHandler("localhost", "username", "password", "database");
$query = $db->query("SELECT * FROM users");
if ($query->num_rows == 1) {
$row = $db->fetchSingleRow($query);
// Handle single row
} elseif ($query->num_rows > 1) {
$rows = $db->fetchMultipleRows($query);
// Handle multiple rows
} else {
// No rows found
}
$query->close();
$db->connection->close();
Keywords
Related Questions
- How can the use of Code Tags improve the readability and organization of code in PHP forum threads?
- In what scenarios would it be more efficient to manually input dropdown options rather than using a loop in PHP?
- How can PHP and MySQL be effectively utilized to store and retrieve data for a weekly calendar-like structure?