# What is PHP PDO? Secure Database Connections & SQL Injection Prevention

https://bihostnet.com/en/knowledgebase/article/php-pdo-secure-database-connection-sql-injection

## Why Use PHP PDO?

PDO (PHP Data Objects) is the modern, secure database abstraction layer in PHP. Deprecated legacy extensions like `mysql_*` were removed in PHP 7. PDO provides cross-database compatibility and built-in protection against SQL Injection.

## Secure Connection Boilerplate

```
$dsn = "mysql:host=localhost;dbname=dbname;charset=utf8mb4";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $username, $password, $options);
```

## Prepared Statements vs SQL Injection

Never concatenate unsanitized user inputs into raw SQL statements. Use prepared statements with named or positional parameters:

```
$stmt = $pdo->prepare("SELECT id, email FROM users WHERE email = :email");
$stmt->execute(['email' => $_POST['email']]);
$user = $stmt->fetch();
```
