ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

PHP Tutorial• 9 min read

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.

PDO Connection and Parameterized Query
<?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.");
  }
?>
Named placeholders (:cat) ensure user input can never tamper with the SQL command syntax.
Pro Tip

Never concatenate user input directly into SQL strings (SELECT * FROM users WHERE email = '$email'). That is the #1 cause of SQL injection.

ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Why are prepared statements in PDO effective against SQL injection?