Loading Depth Study
Preparing your workspace
PDO provides a consistent PHP interface for database access and supports prepared statements for safer SQL execution.
PHP applications frequently need to read and write database records. PDO provides a modern interface for database access and supports prepared statements. Prepared statements separate SQL structure from user-provided values and help protect against SQL injection. Database credentials should remain outside source code. Database connection errors and query failures should also be handled without exposing sensitive details to users.
A PHP course API can use PDO to safely retrieve a course by its ID and update course information.
<?php
$pdo = new PDO(
'mysql:host=localhost;dbname=learning;charset=utf8mb4',
getenv('DB_USER'),
getenv('DB_PASSWORD'),
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$stmt = $pdo->prepare(
'SELECT id, title FROM courses WHERE id = :id'
);
$stmt->execute(['id' => $courseId]);
$course = $stmt->fetch(PDO::FETCH_ASSOC);The PHP application safely retrieves one course using a prepared statement.