CRUD
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "crud_db";
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'] ?? null;
$action = $_GET['action'] ?? '';
$name = '';
$email = '';
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
if ($_POST['action'] === "create") {
$conn->query("INSERT INTO users (name, email) VALUES ('$name', '$email')");
} elseif ($_POST['action'] === "update" && isset($_POST['id'])) {
$id = $_POST['id'];
$conn->query("UPDATE users SET name='$name', email='$email' WHERE id=$id");
}
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
if ($action === "delete" && $id) {
$conn->query("DELETE FROM users WHERE id=$id");
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
if ($action === "edit" && $id) {
$result = $conn->query("SELECT * FROM users WHERE id=$id");
$row = $result->fetch_assoc();
$name = $row['name'];
$email = $row['email'];
}
?>
<!DOCTYPE html>
<html>
<head><title>Single File PHP CRUD</title></head>
<body>
<h2>Simple PHP CRUD (Single File)</h2>
<form method="POST">
<input type="hidden" name="action" value="<?= $action === 'edit' ? 'update' : 'create' ?>">
<?php if ($action === 'edit') echo '<input type="hidden" name="id" value="' . $id . '">'; ?>
Name: <input type="text" name="name" value="<?= htmlspecialchars($name) ?>" required><br><br>
Email: <input type="email" name="email" value="<?= htmlspecialchars($email) ?>" required><br><br>
<input type="submit" value="<?= $action === 'edit' ? 'Update' : 'Add' ?> User">
<a href="<?= $_SERVER['PHP_SELF'] ?>">Cancel</a>
</form>
<h3>User List</h3>
<table border="1" cellpadding="5">
<tr><th>ID</th><th>Name</th><th>Email</th><th>Actions</th></tr>
<?php
$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['id']}</td>
<td>" . htmlspecialchars($row['name']) . "</td>
<td>" . htmlspecialchars($row['email']) . "</td>
<td>
<a href='?action=edit&id={$row['id']}'>Edit</a> |
<a href='?action=delete&id={$row['id']}' onclick='return confirm(\"Delete this user?\")'>Delete</a>
</td>
</tr>";
}
?>
</table>
</body>
</html>
🛠 Setup Steps
-
Create database in phpMyAdmin:
-
Save the above PHP code as
crud.php
in your XAMPPhtdocs
folder. -
Run Apache + MySQL, go to:
Comments
Post a Comment