PHP
PDO Database Queries in PHP
Connect and run prepared statements safely with PDO in PHP.
By EZ4Code Team
pdodatabaseintermediate
Code
<?php
// PDO connection
$pdo = new PDO("mysql:host=localhost;dbname=app", "user", "pass");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepared statement (safe from SQL injection)
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE age > :age");
$stmt->execute(["age" => 18]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Insert
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(["Alice", "[email protected]"]);
echo $pdo->lastInsertId();
// Update
$stmt = $pdo->prepare("UPDATE users SET name = :name WHERE id = :id");
$stmt->execute(["name" => "Bob", "id" => 1]);
// Transaction
try {
$pdo->beginTransaction();
$pdo->exec("DELETE FROM orders WHERE id = 1");
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
echo "Failed: " . $e->getMessage();
}Explanation
Uses PDO with prepared statements (prepare + execute) to prevent SQL injection by separating SQL from data. Named placeholders (:age) or question marks (?) bind values safely, and fetchAll retrieves result rows. Transactions (beginTransaction/commit/rollBack) ensure atomic multi-statement operations.
More PHP Snippets
Arrays and Array Functions in PHP
Create indexed, associative, and multidimensional arrays with map and filter.
String Functions in PHP
Manipulate strings with substr, replace, explode, and sprintf in PHP.
Read and Write Files in PHP
Read, write, append, and iterate files with PHP filesystem functions.
Sessions and Cookies in PHP
Store user data across requests with sessions and cookies in PHP.
Classes and Inheritance in PHP
Define classes with constructors, visibility, and inheritance in PHP.