What are the potential pitfalls of not selecting the database before running a query in PHP?

If the database is not selected before running a query in PHP, the query will not be executed on any specific database, leading to potential errors or unexpected behavior. To solve this issue, always ensure that the database connection is established and the desired database is selected before running any queries.

// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Select the database
$conn->select_db($dbname);

// Run query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Process query results
if ($result->num_rows > 0) {
    // Output data
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close connection
$conn->close();