La base de données MySQL
sql
CREATE TABLE utilisateurs (
id INT AUTO_INCREMENT PRIMARY KEY,
nom VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);
Connexion à la base (db.php)
php
<?php
$host = 'localhost';
$db = 'test_db';
$user = 'root';
$pass = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
} catch (PDOException $e) {
die("Erreur : " . $e.getMessage());
}
?>
Lire les données – Read (index.php)
php
<?php
include 'db.php';
$stmt = $pdo->query("SELECT * FROM utilisateurs");
while ($row = $stmt->fetch()) {
echo $row['nom'] . ' - ' . $row['email'] . ' | ';
echo "<a href='edit.php?id=" . $row['id'] . "'>Modifier</a> | ";
echo "<a href='delete.php?id=" . $row['id'] . "'>Supprimer</a><br>";
}
?>
<br><a href="create.php">Ajouter un utilisateur</a>
Créer – Create (create.php)
php
<?php
include 'db.php';
if (!empty($_POST['nom'])) {
$stmt = $pdo->prepare("INSERT INTO utilisateurs (nom, email) VALUES (?, ?)");
$stmt->execute([$_POST['nom'], $_POST['email']]);
header('Location: index.php');
}
?>
<form method="POST">
Nom : <input type="text" name="nom"><br>
Email : <input type="text" name="email"><br>
<button type="submit">Ajouter</button>
</form>
Mettre à jour – Update (edit.php)
php
<?php
include 'db.php';
$id = $_GET['id'];
if (!empty($_POST['nom'])) {
$stmt = $pdo->prepare("UPDATE utilisateurs SET nom = ?, email = ? WHERE id = ?");
$stmt->execute([$_POST['nom'], $_POST['email'], $id]);
header('Location: index.php');
}
$user = $pdo->prepare("SELECT * FROM utilisateurs WHERE id = ?");
$user->execute([$id]);
$row = $user->fetch();
?>
<form method="POST">
Nom : <input type="text" name="nom" value="<?= $row['nom'] ?>"><br>
Email : <input type="text" name="email" value="<?= $row['email'] ?>"><br>
<button type="submit">Modifier</button>
</form>
Supprimer – Delete (delete.php)
php
<?php
include 'db.php';
if (isset($_GET['id'])) {
$stmt = $pdo->prepare("DELETE FROM utilisateurs WHERE id = ?");
$stmt->execute([$_GET['id']]);
}
header('Location: index.php');
?>
