What are best practices for setting up a database connection in PHP scripts?

Best practices for setting up a database connection in PHP scripts involve using PDO (PHP Data Objects) to connect to the database. This provides a secure and efficient way to interact with the database and helps prevent SQL injection attacks. It is also recommended to store database connection details in a separate configuration file to easily update them in the future.

<?php
// Database connection details
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

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