Set your Publisher ID in src/config/ads.ts to display live ads.
Database Connectivity with PDO & Prepared Statements
Bulletproof database interactions that eliminate SQL injection risks
PHP Data Objects (PDO) provides a consistent, database-agnostic interface for working with relational databases. Using PDO prepared statements completely neutralizes SQL injection vulnerabilities.
Why PDO with Prepared Statements is Mandatory
Database abstraction: PDO works identically across MySQL, PostgreSQL, SQLite, Oracle, and MS SQL Server.
Prepared statements separate the query structure from the untrusted data values. The SQL command is parsed and compiled before user inputs are bound.
Always configure PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION so database failures throw catchable exceptions rather than silent errors.
<?php
$dsn = "mysql:host=localhost;dbname=codexia_db;charset=utf8mb4";
$username = "db_user";
$password = "SecretP@ssw0rd";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $username, $password, $options);
// Secure parameterized query with named placeholder
$stmt = $pdo->prepare("SELECT id, title, price FROM courses WHERE category = :cat AND active = 1");
$stmt->execute(['cat' => 'Backend']);
$courses = $stmt->fetchAll();
foreach ($courses as $c) {
echo "Course: " . htmlspecialchars($c['title']) . " - $" . $c['price'] . "\n";
}
} catch (PDOException $e) {
error_log("Database Connection Error: " . $e->getMessage());
die("Database service temporarily unavailable.");
}
?>Never concatenate user input directly into SQL strings (SELECT * FROM users WHERE email = '$email'). That is the #1 cause of SQL injection.
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Why are prepared statements in PDO effective against SQL injection?