Connecting to a Database with PDO and What’s Next
PDO — PHP’s database toolkit
$pdo = new PDO("mysql:host=localhost;dbname=tutoline", "user", "password");nn$stmt = $pdo->prepare("SELECT name, score FROM students WHERE course = :course");n$stmt->execute(["course" => "PHP"]);nnforeach ($stmt->fetchAll() as $row) {n echo $row["name"] . ": " . $row["score"] . "n";n}
PDO (PHP Data Objects) is a database abstraction layer — the same PDO code works against MySQL, PostgreSQL, SQLite, and several other databases with only the connection string changing, rather than needing to learn a separate library for each one.
Always use prepared statements
The :course placeholder above is a prepared statement parameter — PDO handles escaping it safely, no matter what value is passed in. Building a query by concatenating raw $_POST data directly into a SQL string is precisely how sites become vulnerable to SQL injection — a classic and still extremely common attack where user input is crafted to alter the meaning of your query entirely. Never do that; always use prepared statements for any value coming from outside your own code.
Error handling with PDO
try {n $pdo = new PDO("mysql:host=localhost;dbname=tutoline", "user", "password");n $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);n} catch (PDOException $e) {n echo "Connection failed: " . $e->getMessage();n}
Setting ERRMODE_EXCEPTION makes PDO throw real, catchable exceptions on database errors instead of silently returning false — the far safer default for any real application, since a silently failed query can otherwise go completely unnoticed until much later.
Onward to the advanced lessons
You now know PHP syntax, functions, arrays, form handling, object-oriented PHP, and safe database access. The next three lessons take you to a professional level: namespaces and Composer, traits, and building a small API.