PHP CRUD Create, edit, update and delete posts with MySQL database

Creating, editing, updating and deleting content on a website is what makes the site dynamic. That's what we are going to be doing in this post.

A user who visits our site will be able to create posts that will be saved in a mysql database, retrieve the posts from the database and display them on the web page. Each post will be displayed with an edit and delete button to permit the user to update posts as well as delete them.

First, create a database named crud. In the crud database, create a table called info. The info table should have the following columns:

id - int(11)

name - varchar(100)

address - varchar(100)

Yap! Just two fields. I'm trying to keep things simple here. so, let's move on to the next step.

I usually like to separate my HTML code from my PHP code as much as possible. I consider that good practice. On that note, let's create another file called php_code.php where we implement all php functionalities like connecting to the database, query the database and the like.

Now include this file at the top (the very first line) of your index.php file. Like so:

<?php include('server.php'); ?>

At this point, all that this code does is connect to the database, initialize some variables and saves submitted data from the form to the database in the info we created earlier. That's only the CReate part of CRUD. Let's proceed with the others.

Now visit again your index.php file and add this code right under the <body> tag:

When editting a database record, we need to put the old values in the form so that they can be modified. To do so, let's modify our input fields on the form and set those values taken from the database ($name, $address) as values to the value attribute of the form fields.

Also add a hidden field to hold the id of the record we will be updating so that it can be recognized in the database uniquely by it's id. This explains it better:

Now if we click on the edit button on a particular record from the database, the values will be filled in the form and we will be able to edit them. Since we are editing on the same form as when we are creating, we have to put a condition that determines the appropriate button to be displayed. For example, when editing, we display the update button on the form and when creating, we display the save button. We do this using the update variable which is boolean. When update is true, the update button is displayed and if false, the save button is displayed.

Conclusion

This brings us to the end of this tutorial. I hope it was helpful and worth your time. I am very honored by your patience in having followed this to the end. If you like this tutorial, share it with your friends by clicking on any of the social media icons below. Don't forget to checkout my other tutorials on this site.