<?php
$host = '127.0.0.1';
$db = 'my_database';
$user = 'root';
$pass = 'password123';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
echo "<h2>Database connection established successfully!</h2>";
} catch (\PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
echo "<hr>";
$firstName = 'John';
$lastName = 'Doe';
$email = 'john.doe@example.com';
$sqlInsert = "INSERT INTO users (first_name, last_name, email) VALUES (:first_name, :last_name, :email)";
$stmtInsert = $pdo->prepare($sqlInsert);
$stmtInsert->execute([
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email
]);
$newId = $pdo->lastInsertId();
echo "<strong>[CREATE]</strong> User successfully added with ID: " . $newId . "<br>";
$newEmail = 'john.doe.updated@example.com';
$sqlUpdate = "UPDATE users SET email = :email WHERE id = :id";
$stmtUpdate = $pdo->prepare($sqlUpdate);
$stmtUpdate->execute([
'email' => $newEmail,
'id' => $newId
]);
echo "<strong>[UPDATE]</strong> Email for user ID {$newId} has been updated.<br>";
echo "<hr>";
$stmtSelect = $pdo->query("SELECT id, first_name, last_name, email FROM users");
$users = $stmtSelect->fetchAll();
echo "<h3>[READ] List of users in the database:</h3>";
if (!empty($users)) {
echo '<table border="1" cellpadding="5" style="border-collapse: collapse;">';
echo '<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>E-mail</th></tr>';
foreach ($users as $row) {
echo '<tr>';
echo '<td>' . htmlspecialchars($row['id']) . '</td>';
echo '<td>' . htmlspecialchars($row['first_name']) . '</td>';
echo '<td>' . htmlspecialchars($row['last_name']) . '</td>';
echo '<td>' . htmlspecialchars($row['email']) . '</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo "No users found in the database.<br>";
}
echo "<hr>";
$sqlDelete = "DELETE FROM users WHERE id = ?";
$stmtDelete = $pdo->prepare($sqlDelete);
$stmtDelete->execute([$newId]);
echo "<strong>[DELETE]</strong> Test user with ID {$newId} has been deleted to keep the database clean.";