How can the mysql_query() function be effectively used to fetch and display results in PHP?

To effectively use the mysql_query() function to fetch and display results in PHP, you need to establish a database connection, execute the query, fetch the results, and then display them in a desired format. It is important to handle any potential errors that may occur during the process.

// Establish database connection
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Execute query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Fetch and display results
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

// Close connection
mysqli_close($connection);