What are the recommended methods for handling external database connections in PHP scripts for beginners?

When handling external database connections in PHP scripts, beginners should use PDO (PHP Data Objects) or MySQLi (MySQL Improved) to establish secure and efficient connections. These methods offer prepared statements to prevent SQL injection attacks and provide better error handling capabilities. By using either PDO or MySQLi, beginners can easily connect to databases, execute queries, and fetch results in a safe and reliable manner.

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

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();
}