How can one properly handle errors and connections when using the mysql_connect() function in PHP?

When using the mysql_connect() function in PHP, it is important to properly handle errors and connections to ensure the stability and security of your application. One way to do this is by checking the return value of the function for errors and using the mysql_error() function to get more information about any connection issues that may arise.

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

$conn = mysql_connect($servername, $username, $password);

if (!$conn) {
    die("Connection failed: " . mysql_error());
}

echo "Connected successfully";

mysql_close($conn);
?>