What is the purpose of using a while loop to fetch data from a database in PHP?
When fetching data from a database in PHP, using a while loop is essential to iterate through the result set returned by the database query. This loop allows you to fetch each row of data one by one until there are no more rows left to retrieve. By using a while loop, you can process each row individually and perform any necessary operations on the data.
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to fetch data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Check if there are rows returned
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();
Keywords
Related Questions
- How can PHP efficiently handle the generation and evaluation of millions of combination possibilities for pronounceable strings?
- In what ways can JavaScript be integrated with PHP to enhance chat functionality and user experience on a website?
- What are the benefits of using printf() over echo for generating HTML output in PHP?