What are the best practices for handling database connections and selection in PHP scripts to avoid errors like "No database selected"?

When connecting to a database in PHP, it is essential to select the appropriate database before executing any queries to avoid errors like "No database selected." To ensure that a database is selected, you can explicitly specify the database name in the connection string or use the MySQLi or PDO extension to select the database after establishing the connection.

// Establishing a connection to the database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";

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

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

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