How can PHP be used to retrieve and display data from a database in a web application?

To retrieve and display data from a database in a web application using PHP, you can use PHP's database extensions like PDO or MySQLi to establish a connection to the database, execute a query to fetch the data, and then display the results on the web page using HTML.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Execute a query to fetch data from a table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Display the fetched data on the web page
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>