What are the best practices for structuring PHP scripts to handle database connections and queries efficiently?

To handle database connections and queries efficiently in PHP scripts, it is recommended to use PDO (PHP Data Objects) for database access, prepare statements to prevent SQL injection attacks, and close connections after use to free up resources.

// Establish a database connection using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

// Prepare and execute a query using PDO prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => 1]);
$results = $stmt->fetchAll();

// Close the database connection
$pdo = null;