Course Beginner Free
PDO — The basics
Connect PHP to MySQL with PDO: prepared statements, transactions and error handling.
- 4 guides
- 42 concepts
Guides
- 01 Guide PDO glossary Explain the concepts in your own words and recognise them in an example.
- 02 Guide PDO essentials Choose and use the essential elements to complete this step of the blog.
- 03 Guide PDO workshop · À table ! Reproduce a working result, test it, then succeed at an exercise without copying.
- 04 Guide Resources and review Find reliable information and explain what you have built.
Suggested path
- 01. HTML: structure three recipes in a semantic page.
- 02. CSS: make the blog readable on mobile and on desktop.
- 03. JavaScript: filter the recipes without reloading the page.
- 04. PHP: produce the pages from arrays and process a form.
- 05. MySQL: keep the recipes in a relational database.
- 06. PDO: read and add recipes from PHP with prepared queries.
Sources and references
Beginner workshop, step 6/6. The complete files are materials to reproduce in a separate local project. Read the prerequisites, the expected results and the limits stated in the workshop.
Example files
includes/functions.php
<?php
// Fichier PHP sans balise de fermeture pour éviter les sorties accidentelles.
function h(string $valeur): string
{
return htmlspecialchars($valeur, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function texte(array $donnees, string $cle): string
{
$valeur = $donnees[$cle] ?? '';
return is_string($valeur) ? trim($valeur) : '';
}
includes/db.php
<?php
$utilisateur = getenv('DB_USER');
$motDePasse = getenv('DB_PASSWORD');
if ($utilisateur === false || $utilisateur === '' || $motDePasse === false) {
http_response_code(500);
exit('Configurer DB_USER et DB_PASSWORD dans le terminal du serveur PHP.');
}
$hote = getenv('DB_HOST') ?: '127.0.0.1';
$port = getenv('DB_PORT') ?: '3306';
$base = getenv('DB_NAME') ?: 'blog_recettes';
$dsn = "mysql:host={$hote};port={$port};dbname={$base};charset=utf8mb4";
try {
return new PDO($dsn, $utilisateur, $motDePasse, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $erreur) {
// Ne pas envoyer le DSN, le mot de passe ou le détail technique au visiteur.
error_log('Connexion MySQL indisponible, SQLSTATE : ' . $erreur->getCode());
http_response_code(500);
exit('La base est indisponible. Vérifier la configuration locale du serveur.');
}
public/index.php
<?php
require __DIR__ . '/../includes/functions.php';
$pdo = require __DIR__ . '/../includes/db.php';
$q = texte($_GET, 'q');
$sql = 'SELECT r.id, r.titre, r.duree_minutes, r.portions, c.nom AS categorie
FROM recettes AS r JOIN categories AS c ON c.id = r.categorie_id';
$parametres = [];
if ($q !== '') {
$sql .= ' WHERE r.titre LIKE :recherche';
$parametres['recherche'] = '%' . $q . '%';
}
$sql .= ' ORDER BY r.id';
try {
$requete = $pdo->prepare($sql);
$requete->execute($parametres);
$recettes = $requete->fetchAll();
} catch (PDOException $erreur) {
error_log('Lecture des recettes impossible, SQLSTATE : ' . $erreur->getCode());
http_response_code(500);
exit('Impossible de charger les recettes pour le moment.');
}
?>
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>À table ! · Recettes en base</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="entete"><h1>À table !</h1><a href="ajouter.php">Ajouter une recette</a></header>
<main class="conteneur">
<h2>Nos recettes maison</h2>
<form method="get" action="index.php">
<label for="q">Rechercher par titre</label>
<input id="q" name="q" type="search" value="<?= h($q) ?>">
<button type="submit">Rechercher</button>
<a href="index.php">Tout afficher</a>
</form>
<p><?= count($recettes) ?> recette(s) trouvée(s).</p>
<?php if ($recettes === []): ?><p>Aucune recette trouvée.</p><?php endif; ?>
<div class="recettes">
<?php foreach ($recettes as $recette): ?>
<article class="recette">
<h3><a href="recette.php?id=<?= (int) $recette['id'] ?>"><?= h($recette['titre']) ?></a></h3>
<p class="meta"><?= (int) $recette['duree_minutes'] ?> min · <?= (int) $recette['portions'] ?> personnes · <?= h($recette['categorie']) ?></p>
</article>
<?php endforeach; ?>
</div>
</main>
</body>
</html>
public/recette.php
<?php
require __DIR__ . '/../includes/functions.php';
$id = filter_var($_GET['id'] ?? null, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1],
]);
if ($id === false) {
http_response_code(400);
exit('Identifiant de recette invalide.');
}
$pdo = require __DIR__ . '/../includes/db.php';
try {
$requete = $pdo->prepare(
'SELECT r.id, r.titre, r.duree_minutes, r.portions,
r.ingredients, r.etapes, c.nom AS categorie
FROM recettes AS r JOIN categories AS c ON c.id = r.categorie_id
WHERE r.id = :id'
);
$requete->bindValue(':id', $id, PDO::PARAM_INT);
$requete->execute();
$recette = $requete->fetch();
} catch (PDOException $erreur) {
error_log('Lecture de la fiche impossible, SQLSTATE : ' . $erreur->getCode());
http_response_code(500);
exit('Impossible de charger cette recette pour le moment.');
}
if ($recette === false) {
http_response_code(404);
exit('Recette introuvable.');
}
?>
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= h($recette['titre']) ?> · À table !</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="conteneur">
<a href="index.php">Toutes les recettes</a>
<article class="recette">
<h1><?= h($recette['titre']) ?></h1>
<p><?= (int) $recette['duree_minutes'] ?> min · <?= (int) $recette['portions'] ?> personnes · <?= h($recette['categorie']) ?></p>
<h2>Ingrédients</h2>
<ul><?php foreach (explode("\n", $recette['ingredients']) as $ligne): ?>
<li><?= h($ligne) ?></li>
<?php endforeach; ?></ul>
<h2>Préparation</h2>
<ol><?php foreach (explode("\n", $recette['etapes']) as $ligne): ?>
<li><?= h($ligne) ?></li>
<?php endforeach; ?></ol>
</article>
</main>
</body>
</html>
public/ajouter.php
<?php
// La session doit démarrer avant toute sortie HTML.
session_set_cookie_params(['httponly' => true, 'samesite' => 'Lax']);
session_start();
require __DIR__ . '/../includes/functions.php';
$pdo = require __DIR__ . '/../includes/db.php';
if (!isset($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
$erreurs = [];
$titre = $dureeSaisie = $portionsSaisies = $categorieSaisie = '';
$ingredients = $etapes = '';
try {
$categories = $pdo->query('SELECT id, nom FROM categories ORDER BY nom')->fetchAll();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$jeton = texte($_POST, 'csrf');
if (!hash_equals($_SESSION['csrf'], $jeton)) {
http_response_code(403);
exit('Formulaire expiré ou invalide. Recharger la page avant de réessayer.');
}
$titre = texte($_POST, 'titre');
$dureeSaisie = texte($_POST, 'duree_minutes');
$portionsSaisies = texte($_POST, 'portions');
$categorieSaisie = texte($_POST, 'categorie_id');
// Uniformiser les sauts de ligne Windows et Linux.
$ingredients = str_replace(["\r\n", "\r"], "\n", texte($_POST, 'ingredients'));
$etapes = str_replace(["\r\n", "\r"], "\n", texte($_POST, 'etapes'));
$duree = filter_var($dureeSaisie, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 1440],
]);
$portions = filter_var($portionsSaisies, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 20],
]);
$categorieId = filter_var($categorieSaisie, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1],
]);
if (mb_strlen($titre, 'UTF-8') < 3 || mb_strlen($titre, 'UTF-8') > 120) {
$erreurs[] = 'Le titre doit contenir entre 3 et 120 caractères.';
}
if ($duree === false) { $erreurs[] = 'La durée doit être un entier entre 1 et 1440.'; }
if ($portions === false) { $erreurs[] = 'Les portions doivent être un entier entre 1 et 20.'; }
if ($ingredients === '' || mb_strlen($ingredients, 'UTF-8') > 5000) {
$erreurs[] = 'Renseigner les ingrédients, au maximum 5000 caractères.';
}
if ($etapes === '' || mb_strlen($etapes, 'UTF-8') > 10000) {
$erreurs[] = 'Renseigner les étapes, au maximum 10000 caractères.';
}
$categorieExiste = false;
if ($categorieId !== false) {
foreach ($categories as $categorie) {
if ((int) $categorie['id'] === $categorieId) {
$categorieExiste = true;
break;
}
}
}
if (!$categorieExiste) { $erreurs[] = 'Choisir une catégorie existante.'; }
if ($erreurs === []) {
$requete = $pdo->prepare(
'INSERT INTO recettes (titre, duree_minutes, portions, ingredients, etapes, categorie_id)
VALUES (:titre, :duree, :portions, :ingredients, :etapes, :categorie)'
);
$requete->bindValue(':titre', $titre, PDO::PARAM_STR);
$requete->bindValue(':duree', $duree, PDO::PARAM_INT);
$requete->bindValue(':portions', $portions, PDO::PARAM_INT);
$requete->bindValue(':ingredients', $ingredients, PDO::PARAM_STR);
$requete->bindValue(':etapes', $etapes, PDO::PARAM_STR);
$requete->bindValue(':categorie', $categorieId, PDO::PARAM_INT);
$requete->execute();
$nouvelId = (int) $pdo->lastInsertId();
// Redirection vers une lecture : actualiser la fiche ne répète pas le POST.
header('Location: recette.php?id=' . $nouvelId, true, 303);
exit;
}
}
} catch (PDOException $erreur) {
error_log('Opération sur les recettes impossible, SQLSTATE : ' . $erreur->getCode());
http_response_code(500);
exit('Impossible de terminer cette opération pour le moment.');
}
?>
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ajouter une recette · À table !</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="conteneur">
<a href="index.php">Toutes les recettes</a>
<h1>Ajouter une recette</h1>
<?php if ($erreurs !== []): ?>
<div role="alert"><ul><?php foreach ($erreurs as $erreur): ?>
<li><?= h($erreur) ?></li>
<?php endforeach; ?></ul></div>
<?php endif; ?>
<form method="post" action="ajouter.php">
<input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
<p><label for="titre">Titre</label><br>
<input id="titre" name="titre" required minlength="3" maxlength="120" value="<?= h($titre) ?>"></p>
<p><label for="duree_minutes">Durée en minutes</label><br>
<input id="duree_minutes" name="duree_minutes" type="number" required min="1" max="1440" value="<?= h($dureeSaisie) ?>"></p>
<p><label for="portions">Nombre de personnes</label><br>
<input id="portions" name="portions" type="number" required min="1" max="20" value="<?= h($portionsSaisies) ?>"></p>
<p><label for="categorie_id">Catégorie</label><br>
<select id="categorie_id" name="categorie_id" required>
<option value="">Choisir une catégorie</option>
<?php foreach ($categories as $categorie): ?>
<option value="<?= (int) $categorie['id'] ?>" <?= $categorieSaisie === (string) $categorie['id'] ? 'selected' : '' ?>><?= h($categorie['nom']) ?></option>
<?php endforeach; ?>
</select></p>
<p><label for="ingredients">Ingrédients (un par ligne)</label><br>
<textarea id="ingredients" name="ingredients" required maxlength="5000" rows="6"><?= h($ingredients) ?></textarea></p>
<p><label for="etapes">Préparation (une étape par ligne)</label><br>
<textarea id="etapes" name="etapes" required maxlength="10000" rows="6"><?= h($etapes) ?></textarea></p>
<button type="submit">Enregistrer la recette</button>
</form>
</main>
</body>
</html>
In the same series Step 6 of 6
- 1 Course HTML — The basics
- 2 Course CSS — The basics
- 3 Course JavaScript — The basics
- 4 Course PHP — The basics
- 5 Course MySQL — The basics
-
6 Course PDO — The basics You are here
In the same category
Development and production · Beginner
HTML — The basics
Build a semantic, accessible web page step by step with a running project: a recipe mini-blog.
Development and production · Intermediate
Node.js — The fundamentals
Understand the Node.js runtime: modules, asynchronous code, npm and building a small server.
Development and production · Beginner
CSS — The basics
Style the recipe mini-blog and make it responsive: selectors, box model, flexbox, grid and mobile-first.