How can PDO be effectively used in conjunction with include statements in PHP scripts?
When using PDO in conjunction with include statements in PHP scripts, it is important to establish a database connection in a separate file and include that file in any scripts that require database access. This helps to centralize the database connection logic and ensures that it is consistently used across all scripts.
// db_connect.php
$host = 'localhost';
$dbname = 'database';
$username = 'root';
$password = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
```
```php
// index.php
include 'db_connect.php';
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
$users = $stmt->fetchAll();
foreach ($users as $user) {
echo $user['username'] . "<br>";
}