# PHP PDO (Database Access)

**PDO** (PHP Data Objects) defines a lightweight, consistent interface for accessing databases in PHP. Unlike the old `mysql_` functions or `mysqli`, PDO supports multiple database types (MySQL, PostgreSQL, SQLite, etc.) using the same functions.

---

## 1. Connecting to a Database
To connect, you create a new instance of the `PDO` class. It is best practice to wrap this in a `try...catch` block to handle connection errors gracefully.

```php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
```

## 2. Selecting Data
You can use `query()` for static queries, but `prepare()` is preferred for anything involving variables.

```php
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();

// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
    echo $v['firstname'] . "<br>";
}
```

## 3. Prepared Statements (Security)
Prepared statements are the most effective way to prevent **SQL Injection**. The database compiles the SQL template first, and then binds the user input to the placeholders.

```php
// Prepare
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)");

// Bind parameters
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

// Set values and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
```

## 4. Closing the Connection
The connection is automatically closed when the script ends, but you can close it manually by setting the object to `null`.

```php
$conn = null;
```

[[programming/php/php]] [[programming/php/php-security]]