How can error handling be improved in PHP scripts that interact with databases, especially when executing queries using mysql_query?

When interacting with databases in PHP, especially when executing queries using `mysql_query`, it is essential to implement proper error handling to catch and handle any potential issues that may arise during database operations. One way to improve error handling is to check the return value of `mysql_query` for errors and handle them accordingly, such as by displaying an error message or logging the error for further investigation.

// Connect to database
$connection = mysql_connect("localhost", "username", "password");
if (!$connection) {
    die("Error connecting to the database: " . mysql_error());
}

// Select the database
$db_selected = mysql_select_db("database_name", $connection);
if (!$db_selected) {
    die("Error selecting database: " . mysql_error());
}

// Execute query
$query = "SELECT * FROM table_name";
$result = mysql_query($query, $connection);
if (!$result) {
    die("Error executing query: " . mysql_error());
}

// Process the results
while ($row = mysql_fetch_assoc($result)) {
    // Do something with the data
}

// Close the connection
mysql_close($connection);