CRUD operations using PHP and MySQL

In our previous article, we explored how to establish a connection between PHP and MySQL, and how to retrieve data from the database and display it on a webpage. We covered the fundamental concepts of setting up a local server environment, writing a basic connection script, and executing a simple SELECT query.

In this article, we will take things a step further by implementing full CRUD operations — Create, Read, Update, and Delete — using PHP and MySQL. We will build a practical user management system that includes a registration form with validation, a login system using sessions and cookies, and a dynamic user listing table with edit and delete functionality. By the end of this article, you will have a fully functional mini-application demonstrating all four CRUD operations in action.

Table of Contents:

  1. Database and Table Setup
  2. Database Connection
  3. User Registration Form with Validation
  4. User Login Form
  5. Dashboard page with Session data and Users table
  6. Edit User Data
  7. Delete User Data
  8. Conclusion

1 – Database and Table Setup

First, open phpMyAdmin or your MySQL client and create a new database named Customers. Inside this database, we will create table named users.

The users table stores complete user profile data like first name, last name, gender, city, email, and password.

2 – Database Connection

Create a file named db_connection.php in the project directory. This file will be included in every PHP file that requires database access.

3 – User Registration Form with Validation

Create a file named register.php in the project directory. This file contains the HTML registration form along with PHP-based server-side validation.

Validation Rules:

  • First Name, Last Name, City: Must start with a letter (a–z or A–Z). No numbers or special characters allowed.
  • Email: Must follow a valid email pattern.
  • Gender: Selected via radio buttons (Male / Female).
  • Password: Must be alphanumeric with at least one special character, minimum 8 characters, maximum 15 characters.

First, we will set up the user interface by creating the form structure and applying visual styles. Open register.php and add the HTML form structure.

Open style.css and add custom styles to design the form.

Next, we will handle user input securely by implementing server-side logic. Open register.php again. Insert the PHP validation and submission code at the very top of the file.

Note: For production applications, always use prepared statements to prevent SQL injection.

4 – User Login Form

After a successful registration, the user is redirected to the login page. We will now build the login interface and its authentication logic. Create a new file named login.php. Add the HTML login form markup into this file.

Next, we will connect the form to the database to validate credentials and securely log the user in. Open login.php and insert the PHP authentication code at the very top, before the HTML markup.

This PHP script will check the entered email and password against the users table. Redirect the user to the Dashboard page upon a successful match.

5 – Dashboard page with Session data and Users table

We will create a dashboard.php page that greets the logged-in user and displays all users from the database in a table.

At the very top of dashboard.php, start the session and include the database connection file.

session_start() must be called before any output is sent to the browser. The include 'db_connection.php' line loads the database connection so we can query the users table.

Only logged-in users should be able to access the dashboard. We check whether the session has a user_id value. If not, the user is redirected back to the login page.

The exit after header() is important — it stops the rest of the script from running after the redirect.

Now we run a query to fetch all records from the users table.

We store the result in $result, which we will loop through later in the HTML.

Inside the HTML, we greet the logged-in user by name using the value stored in the session. We use htmlspecialchars() to prevent XSS (Cross-Site Scripting) attacks.

You can place a Logout link next to the welcome message so the user can easily sign out.

We create an HTML table with columns for ID, Name, Gender, City, Email, and Actions.

We use a while loop with mysqli_fetch_assoc() to go through each row returned from the database and print it as a table row.

Each row has an Edit link that goes to edit.php and a Delete link that goes to delete.php, both passing the user’s id as a URL parameter. The delete link includes a JavaScript confirmation dialog so the user does not accidentally delete a record.

6 – Edit User Data

When a user clicks the Edit button on the dashboard, the browser redirects them to edit.php with the URL carrying the user’s ID like this:

Now let’s build the edit.php page step by step.

Just like on the dashboard page, we start the session and include the database connection at the very top.

We make sure only logged-in users can access the edit page. If PHP finds no session, the browser sends the user back to the login page.

When the user clicks the Edit button on the dashboard, PHP passes the user’s ID through the URL as a query parameter. We read that value using $_GET['id'].

We cast it to an integer with (int) to make sure no harmful input can be passed through the URL.

Using the ID from the URL, we query the database to fetch that specific user’s current details. This data will be used to pre-fill the edit form so the user can see the existing values before making changes.

When the user updates the form and clicks the submit button, the form data is sent via POST. We check for the form submission and run an UPDATE query to save the changes to the database.

After a successful update, the browser redirects the user back to the dashboard.

In the HTML, we display a form pre-filled with the user’s current data using the $row values we fetched. This way the user can see what is already saved and only change what they need to.

It is good practice to give the user a way to cancel and go back to the dashboard without making any changes.

That’s it! With these steps, edit.php page will read the user ID from the URL, load that user’s current data into a form, and save the updated values back to the database when the user submits the form.

7 – Delete User Data

When a user clicks the Delete link on the dashboard, a JavaScript confirmation alert appears first asking the user to confirm the action. The onclick attribute on the delete link handles this behavior directly on the dashboard.

If the user clicks OK, the browser redirects them to delete.php with the user’s ID in the URL. If they click Cancel, nothing happens and they stay on the dashboard.

Now let’s build the delete.php file step by step.

We start the session and include the database connection at the top of the file.

We check whether the user is logged in. If PHP finds no session, the browser redirects them back to the login page so unauthorized users cannot directly access this file via the URL.

We read the id value passed through the URL. The ?? null coalescing operator sets a default value of 0 if no ID is provided in the URL.

Before running any database query, we validate the ID to make sure it is a positive number. If the ID is missing, non-numeric, or zero, the user is sent back to the dashboard and no delete operation takes place.

This is an important security step that prevents invalid or malicious values from reaching the database.

Instead of inserting the ID directly into the query string, we use a prepared statement. This protects the database from SQL injection attacks.

The ? is a placeholder for the ID value. The bind_param( “i”, $id ) line binds the actual ID to that placeholder, where "i" tells PHP the value is an integer.

We execute the prepared statement to delete the user from the database. Once done, the user is immediately redirected back to the dashboard where the updated users list will no longer include the deleted record.

That’s it! With these steps, your delete.php page will safely read the user ID from the URL, validate it, and permanently remove that user from the database using a prepared statement before sending the user back to the dashboard.

8 – Conclusion

In this article, we successfully implemented all four CRUD operations — Create, Read, Update, and Delete — using PHP and MySQL. We built a complete user management system that includes a validated registration form, a secure login system using sessions, a dynamic user listing table, and fully functional edit and delete capabilities. These are the core building blocks of virtually every web application. In our upcoming articles, we will explore how to make this system more secure using prepared statements and how to enhance the UI using Bootstrap. Stay tuned!

Leave a Comment