How can the "No Database Selected!" error be resolved in PHP when using mysql_query()?

The "No Database Selected!" error occurs when the PHP script attempts to run a query using mysql_query() without specifying the database to use. To resolve this issue, you need to first establish a connection to the MySQL server and select the database before executing any queries.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_database_name";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

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

// Select the database
mysqli_select_db($conn, $dbname);

// Run your query
$result = mysqli_query($conn, "SELECT * FROM your_table");

// Process the query result
if (mysqli_num_rows($result) > 0) {
    // Output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close connection
mysqli_close($conn);
?>