PHP 8 Basics & PDO Database Connection

6 min read PHP 417 views

Secure Database Access with PHP PDO

PHP Data Objects (PDO) provides a consistent, secure database abstraction interface. Always use prepared statements to prevent SQL Injection attacks!

Why Prepared Statements?

Prepared statements separate SQL instructions from user-supplied parameters. The database compiles the SQL template first, making parameter injection impossible.

php Example
Run Code
<?php
// Secure PDO Connection
$host = "localhost";
$db   = "codingrider";
$user = "root";
$pass = "";
$charset = "utf8mb4";

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$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, $user, $pass, $options);
    echo "Connected successfully to CodingRider DB!";
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}
?>

Related Tutorials