$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password'); $stmt = $db->query('SELECT * FROM users'); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($results as $row) { echo $row['name'] . ' - ' . $row['email'] . '
'; }
$db = new PDO('pgsql:host=localhost;dbname=mydatabase', 'username', 'password'); $stmt = $db->prepare('INSERT INTO orders (order_id, customer_name, order_total) VALUES (?, ?, ?)'); $stmt->execute([12345, 'John Doe', 99.99]);
$db = new PDO('sqlite:/path/to/database.sqlite'); $stmt = $db->prepare('UPDATE users SET email = ? WHERE id = ?'); $stmt->execute(['newemail@example.com', 123]);In this example, we create a connection to a SQLite database and update the `email` field for a user with `id` of 123 in the `users` table. The `prepare()` method creates a prepared statement with placeholders for the values to be updated. The `execute()` method then executes the statement with the specified values. Overall, PDO is a useful package library for performing PHP database queries due to its flexibility in working with various database systems and its support for prepared statements which help prevent SQL injection attacks.