How can a PHP developer ensure that all results from a MySQL query are displayed, rather than just the first result?
To ensure that all results from a MySQL query are displayed in PHP, a developer can use a loop to fetch each row of the result set and display it. By iterating through all the rows returned by the query, the developer can ensure that all results are displayed rather than just the first one.
// Connect to MySQL database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Run MySQL query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Check if there are any results
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close MySQL connection
$conn->close();