What is the correct syntax for retrieving and displaying data from a MySQL database using PHP?

To retrieve and display data from a MySQL database using PHP, you need to establish a connection to the database, execute a query to fetch the data, and then loop through the results to display them on the webpage. Make sure to handle any errors that may occur during the database interaction.

<?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
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Loop through the results and display them
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>