What is the recommended method for accessing a database in PHP, using PDO or other methods?

When accessing a database in PHP, it is recommended to use PDO (PHP Data Objects) due to its security features and flexibility. PDO allows you to connect to different types of databases easily and provides prepared statements to prevent SQL injection attacks.

// Connect to database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected to database successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}