What are the recommended database connection methods in PHP, and why is the use of mysqli or PDO preferred over the older mysql functions?

The recommended database connection methods in PHP are mysqli and PDO. These methods provide better security features such as prepared statements to prevent SQL injection attacks. It is preferred to use mysqli or PDO over the older mysql functions because they offer improved performance, support for more database drivers, and are actively maintained by the PHP community.

// Using PDO to connect to a database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}