How can the mysql_select_db function be correctly used in PHP code to avoid errors?

When using the mysql_select_db function in PHP, it is important to establish a connection to the MySQL server using mysql_connect before selecting the database. This ensures that the function has a valid connection to work with. Additionally, it is recommended to check for errors and handle them appropriately to avoid unexpected behavior in your code.

// Establish a connection to the MySQL server
$connection = mysql_connect("localhost", "username", "password");

// Check if the connection was successful
if (!$connection) {
    die("Connection failed: " . mysql_error());
}

// Select the database
$database = "database_name";
if (!mysql_select_db($database, $connection)) {
    die("Database selection failed: " . mysql_error());
}

// Your code here