MySQL Intro

Connect PHP to MySQL and understand safe database access patterns.

On this page

Why PDO

Use PDO for database access in modern PHP. It supports prepared statements, consistent error handling, and cleaner code. In production code, you should avoid building SQL by concatenating user input.

What a DB Connection Does

A DB connection lets your app read and write data. In a typical request, your code reads input, validates it, runs queries, and returns HTML or JSON.

Minimal PDO Example

This example shows the shape: connect, query, fetch. We will go deeper in the next lessons.

<?php
$dsn = "mysql:host=127.0.0.1;dbname=app;charset=utf8mb4";
$user = "root";
$pass = "";

$pdo = new PDO($dsn, $user, $pass);

$stmt = $pdo->query("SELECT NOW() AS now_time");
$row = $stmt->fetch(PDO::FETCH_ASSOC);

echo $row["now_time"];

Production Tip

Use UTF-8 (utf8mb4), use prepared statements for any user input, and configure error handling + logging so you do not expose raw DB errors to users.