Complete PHP CRUD Guide with Apache & SQL
Complete PHP CRUD Guide
Building a CRUD Application with PHP, MySQL, and Apache Server
Introduction to PHP CRUD
CRUD stands for Create, Read, Update, and Delete - the four basic operations of persistent storage. In this guide, we'll build a complete web application that demonstrates all these operations using PHP and MySQL, running on an Apache server.
We'll create a simple user management system where you can add, view, edit, and delete user records from a database.
Prerequisites
Before we begin, make sure you have the following installed:
- Apache HTTP Server - Web server to run PHP files
- PHP (7.4 or higher) - Server-side scripting language
- MySQL (5.7 or higher) / MariaDB - Database management system
- phpMyAdmin (Optional) - Web-based database administration tool
- Text Editor/IDE - VS Code, Sublime Text, PHPStorm, etc.
Setting Up Apache and PHP Environment
Download and install XAMPP from apachefriends.org or MAMP from mamp.info.
Open the control panel and start both Apache and MySQL services. Make sure they're running without errors.
Open your browser and navigate to http://localhost. You should see the XAMPP/MAMP welcome page.
Navigate to http://localhost/phpmyadmin to access the database management interface.
Setting Up the Database
First, let's create a database and a table for our user management system.
CREATE DATABASE php_crud_app;
USE php_crud_app;
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone VARCHAR(20),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
You can run this SQL code in phpMyAdmin's SQL tab or through the command line.
Project File Structure
Create the following folder and file structure in your Apache document root (usually htdocs or www):
├── index.php # Home page (list all users)
├── create.php # Create new user form
├── edit.php # Edit user form
├── delete.php # Delete user confirmation
├── process.php # Process form submissions (create/update)
├── config/
│ └── database.php # Database connection file
├── css/
│ └── style.css # Optional CSS file
└── README.md # Project documentation
Database Configuration File
Create config/database.php to handle database connections:
<?php
// Database configuration
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', ''); // Empty for XAMPP default
define('DB_NAME', 'php_crud_app');
// Create connection
function getDatabaseConnection() {
$conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
return $conn;
}
?>
Create Operation
1. Create Form (create.php)
<?php include 'config/database.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Add New User</title>
</head>
<body>
<h2>Add New User</h2>
<form action="process.php" method="POST">
<input type="hidden" name="action" value="create">
First Name: <input type="text" name="first_name" required><br>
Last Name: <input type="text" name="last_name" required><br>
Email: <input type="email" name="email" required><br>
Phone: <input type="text" name="phone"><br>
<input type="submit" value="Add User">
</form>
<a href="index.php">View All Users</a>
</body>
</html>
2. Process Creation (process.php - create part)
<?php
include 'config/database.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$action = $_POST['action'];
$conn = getDatabaseConnection();
if ($action == 'create') {
// Create new user
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$sql = "INSERT INTO users (first_name, last_name, email, phone)
VALUES ('$first_name', '$last_name', '$email', '$phone')";
if (mysqli_query($conn, $sql)) {
header('Location: index.php?msg=User added successfully');
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
}
?>
Read Operation
Display All Users (index.php)
<?php
include 'config/database.php';
$conn = getDatabaseConnection();
// Fetch all users
$sql = "SELECT * FROM users ORDER BY created_at DESC";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>User Management System</title>
</head>
<body>
<h2>User Management System</h2>
<?php if (isset($_GET['msg'])): ?>
<div style="color:green;">
<?php echo $_GET['msg']; ?>
</div>
<?php endif; ?>
<a href="create.php">Add New User</a>
<table border="1" cellpadding="10">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
<th>Created At</th>
<th>Actions</th>
</tr>
<?php
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['created_at'] . "</td>";
echo '<td><a href="edit.php?id=' . $row['id'] . '">Edit</a> | ';
echo '<a href="delete.php?id=' . $row['id'] . '">Delete</a></td>';
echo "</tr>";
}
} else {
echo '<tr><td colspan="7">No users found</td></tr>';
}
mysqli_close($conn);
?>
</table>
</body>
</html>
Update Operation
1. Edit Form (edit.php)
<?php
include 'config/database.php';
$conn = getDatabaseConnection();
// Get user data
$id = intval($_GET['id']);
$sql = "SELECT * FROM users WHERE id = $id";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit User</title>
</head>
<body>
<h2>Edit User</h2>
<form action="process.php" method="POST">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id" value="<?php echo $user['id']; ?>">
First Name: <input type="text" name="first_name" value="<?php echo $user['first_name']; ?>" required><br>
Last Name: <input type="text" name="last_name" value="<?php echo $user['last_name']; ?>" required><br>
Email: <input type="email" name="email" value="<?php echo $user['email']; ?>" required><br>
Phone: <input type="text" name="phone" value="<?php echo $user['phone']; ?>"><br>
<input type="submit" value="Update User">
</form>
<a href="index.php">Back to User List</a>
</body>
</html>
2. Process Update (process.php - update part)
elseif ($action == 'update') {
// Update existing user
$id = intval($_POST['id']);
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$sql = "UPDATE users SET first_name='$first_name', last_name='$last_name', email='$email', phone='$phone' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
header('Location: index.php?msg=User updated successfully');
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
Delete Operation
Delete Confirmation (delete.php)
<?php
include 'config/database.php';
if (isset($_GET['id'])) {
$id = intval($_GET['id']);
$conn = getDatabaseConnection();
// Fetch user for confirmation
$sql = "SELECT * FROM users WHERE id = $id";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<title>Delete User</title>
</head>
<body>
<h2>Delete User</h2>
<p>Are you sure you want to delete user:</p>
<p><?php echo $user['first_name'] . ' ' . $user['last_name']; ?></p>
<p>Email: <?php echo $user['email']; ?></p>
<form action="process.php" method="POST">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?php echo $user['id']; ?>">
<input type="submit" value="Yes, Delete User">
</form>
<a href="index.php">No, Go Back</a>
</body>
</html>
<?php
mysqli_close($conn);
} else {
header('Location: index.php');
}
?>
Process Deletion (process.php - delete part)
elseif ($action == 'delete') {
// Delete user
$id = intval($_POST['id']);
$sql = "DELETE FROM users WHERE id = $id";
if (mysqli_query($conn, $sql)) {
header('Location: index.php?msg=User deleted successfully');
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
}
Testing the Application
Open your browser and navigate to http://localhost/php-crud-app/
Click "Add New User", fill out the form, and submit. Verify the user appears in the list.
Verify all users are displayed correctly in the main table.
Click "Edit" on any user, modify their information, and save. Verify changes appear.
Click "Delete" on any user, confirm deletion, and verify the user is removed from the list.
Live Demo Simulation
Your CRUD application should now be fully functional with:
- Ability to add new users to the database
- Display all users in a table with edit/delete options
- Edit existing user information
- Delete users with confirmation
- Success/error messages for user feedback
Security Considerations
| Security Issue | Solution |
|---|---|
| SQL Injection | Use prepared statements with mysqli or PDO instead of mysqli_real_escape_string |
| XSS (Cross-Site Scripting) | Use htmlspecialchars() when outputting user data to HTML |
| CSRF (Cross-Site Request Forgery) | Use CSRF tokens in forms |
| Session Security | Implement proper session management and authentication |
| Input Validation | Validate all user inputs on both client and server side |
Improved Prepared Statement Example
// Using prepared statements for security
$stmt = $conn->prepare("INSERT INTO users (first_name, last_name, email, phone) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $first_name, $last_name, $email, $phone);
$stmt->execute();
