This blog will explain you how to perform CRUD (Create, Read, Update and Delete) operation (You can also say Insert, Select, Update and Delete operations) in PHP.

Prerequisites:

  • WAMP or XAMPP
  • Language Core PHP
  • Editor: Notepad++, Brackets, Sublime etc...

Now follow the steps to perform operation.

Create Database and Table

Step 1. First of all you have to run xampp or wamp and if you use xampp then you have to start Apache and MySQL.

Step 2. Now type http://localhost/phpmyadmin in url section of browser and it will open phpMyAdmin which may look like this.

Step 3. Click on Database tab. It will open new screen. Give appropriate name of the database and then click on Create button. Database created and show on the left panel of the screen. Here I have given database name as “sample”.

Step 4. Now create a table and columns for storing data. Create table option will display when you open your database. In this you have to give appropriate table name (i.e tblRegistration) and Number of columns that you want and then click on Go button.

Step 5. After clicking on Go button it will open below screen.

Step 6. Write proper name of columns with their data type and length according to your requirement. 

Note: First field of my table is RegId and this field is unique so give Primary Key to it and set Auto Increment (for that you have check A_I Checkbox).When you click  on A_I checkbox one window will appear. In that window you have to click only Go button.

Step 7. After that you have to give all the field name, set data type and write length then simple click on Save button.

Step 8. After clicking on Save button your table created and you can see it on left panel of screen below the database name like this. 

Step 9. Then click on table you can see the structure of that table. In structure you can see all the field name, data type and length which you defined.

Note: If you want to do any changes in particular filed then there is one option Change. Click on that then one screen will display in which you can do changes that you want. To save all changes click on Save button.

If you want to remove particular column then there is one option Drop. When you click on drop one popup open in that if you click on Ok button column remove from database.

If you have to add new column then there is one option Add Column in that in first box you have to write how many column you want to add and in dropdown you have to select after which column you want to add column then click on Go button. Then you have to fill appropriate detail for particular column and then click on Save button that column will display in Structure.

Design and Coding webpage

Now you have to create one folder. If you use wamp then create folder into C:\wamp\www\ folder and if you use xampp then create folder in C:\xampp\htdocs\ folder and give appropriate name to folder.

Insert Operation

Step 1. Create a file to design and code registration page and save that file with .php extension in that particular folder. I created file registration.php. Below the code for registration page.

registration.php

<?php

    $con = new mysqli("localhost","root","","sample");   /* Connection code(Connect with database) */

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Registartion</title>

    <style>

        input[type=text],input[type=email],input[type=password]{

            width:100% !important;

        }

        table{

            border: 1px solid rgb(202,207,210);

        }

        form {

            margin: 10% auto 0;

        }

    </style>

</head>

<body>

   <?php

   /* Start Update Code */

      if(isset($_REQUEST["btnupdate"]))   /* Update button click event.. */

      {

            $checkbox1=$_REQUEST['chkhobby'];  

            $chk="";  

            foreach($checkbox1 as $chk1)  

            {  

              if($chk == "")

              {

                $chk .= $chk1;

              }

              else

      {

              $chk .= ",".$chk1;  

              }   

            }  

            $image="";

            if($_FILES["profile"]["name"]=="")

            {

                $image=$_REQUEST["txtimg"];

            }

            else

            {

                unlink("images//".$_REQUEST["txtimg"]);

                move_uploaded_file($_FILES["profile"]["tmp_name"],"images/".$_FILES["profile"]["name"]);

                $image=$_FILES["profile"]["name"];

            }

            $data = $con->query("update tblregistration set RegFullName='".$_REQUEST["txtfname"]."',RegEmail='".$_REQUEST["txtuemail"]."',RegPassword='".$_REQUEST["txtpassword"]."',RegGender='".$_REQUEST["rdogender"]."',RegHobbies='".$chk."',RegProfile='".$image."' where RegId='".$_REQUEST["txtid"]."'");

            if($data == TRUE)

            {

                echo "<script>alert('Data updated successfully..!');window.location='display.php';</script>";   

            }

            else

            {

                echo "<script>alert('Error while updating..!!')</script>";

            }

        }

  

        if(isset($_REQUEST["btncancel"]))   /* Cancel button click event.. */

        {

            echo "<script>window.location='display.php';</script>";   

        }

/* End update code */

   ?>

  

    <?php

        /* Click on edit from display page check variable that you send from that page and fetch data of that variable. */

if(isset($_REQUEST["isEdit"]))

        {

            $rs = $con->query("select * from tblregistration where RegId='".$_REQUEST["isEdit"]."'") or die(mysqli_error($con));

            while($row = mysqli_fetch_array($rs))

            {

                $ch1 = $ch2 = $ch3 = "";

  $myArray = explode(',', $row["RegHobbies"]);

  foreach($myArray as $chk)

  {

    if($chk == "Cricket")

       {

  $ch1 = 'checked';

       }  

    if($chk == "Hocky")

       {

  $ch2 = 'checked';

       }

    if($chk == "Singing")

       {

  $ch3 = 'checked';

       }

     }

    ?>

       /* Second form when click on edit from display page then this form execute. */

        <form method="post" enctype="multipart/form-data">

          <input type="hidden" name="txtimg" value="<?php echo $row["RegProfile"]; ?>">

          <input type="hidden" name="txtid" value="<?php echo $row["RegId"]; ?>">

           <center><h1>Registration Form</h1></center>

            <table align="center" border="0">

                <tr>

                    <td>Full Name:</td>

                    <td><input type="text" name="txtfname" value="<?php echo $row["RegFullName"]; ?>"></td>

                </tr>

                <tr>

                    <td>Email Address:</td>

                    <td><input type="email" name="txtuemail" value="<?php echo $row["RegEmail"]; ?>"></td>

                </tr>

                <tr>

                    <td>Password:</td>

                    <td><input type="password" name="txtpassword" value="<?php echo $row["RegPassword"]; ?>"></td>

                </tr>

                <tr>

                    <td>Gender:</td>

                    <td>

                        <?php

                            if($row["RegGender"] == "Male")

                            {

                        ?>

                        <input type="radio" name="rdogender" value="Male" checked="true">Male<input type="radio" name="rdogender" value="Female">Female

                        <?php

                            }if($row["RegGender"] == "Female")

                            {

                        ?>

                        <input type="radio" name="rdogender" value="Male">Male<input type="radio" name="rdogender" value="Female" checked="true">Female

                        <?php } ?>

                    </td>

                </tr>

                <tr>

                    <td>Hobbies</td>

                    <td><input type="checkbox" name="chkhobby[]" value="Cricket" <?php if ($ch1 == 'checked') echo "checked='checked'"; ?>>Cricket

                    <input type="checkbox" name="chkhobby[]" value="Hocky" <?php if ($ch2 == 'checked') echo "checked='checked'"; ?>>Hocky

                    <input type="checkbox" name="chkhobby[]" value="Singing" <?php if ($ch3 == 'checked') echo "checked='checked'"; ?>>Singing</td>

                </tr>

                <tr>

                    <td>Profile Picture:</td>

                    <td><input type="file" name="profile"><br/><img src="images/<?php echo $row["RegProfile"]; ?>" alt="User Profile" height="100" width="100"></td>

                </tr>

                <tr>

                    <td colspan="2" align="center"><input type="submit" value="Update" name="btnupdate"> <input type="submit" value="Cancel" name="btncancel"></td>

                </tr>

            </table>

        </form>

    <?php

            }

        }else{

    ?>

    /* Insert form */

    <form method="post" enctype="multipart/form-data">

       <center><h1>Registration Form</h1></center>

        <table align="center" border="0">

            <tr>

                <td>Full Name:</td>

                <td><input type="text" name="txtfname"></td>

            </tr>

            <tr>

                <td>Email Address:</td>

                <td><input type="email" name="txtuemail"></td>

            </tr>

            <tr>

                <td>Password:</td>

                <td><input type="password" name="txtpassword"></td>

            </tr>

            <tr>

                <td>Gender:</td>

                <td><input type="radio" name="rdogender" value="Male">Male<input type="radio" name="rdogender" value="Female">Female</td>

            </tr>

            <tr>

                <td>Hobbies</td>

                <td><input type="checkbox" name="chkhobby[]" value="Cricket">Cricket

                <input type="checkbox" name="chkhobby[]" value="Hocky">Hocky

                <input type="checkbox" name="chkhobby[]" value="Singing">Singing</td>

            </tr>

            <tr>

                <td>Profile Picture:</td>

                <td><input type="file" name="profile"></td>

            </tr>

            <tr>

                <td colspan="2" align="center"><input type="submit" value="Insert" name="btninsert"></td>

            </tr>

        </table>

    </form>

    <?php } ?>

  

    <?php

/* Insert Code Start */

        if(isset($_POST["btninsert"]))   /* Insert button click event */

        {

    /* Move image into images folder which you have to create in C:\xampp\htdocs\foldername\ */

            move_uploaded_file($_FILES["profile"]["tmp_name"],"images/".$_FILES["profile"]["name"]); 

    $image=$_FILES["profile"]["name"];

    $checkbox1=$_POST['chkhobby'];  

    $chk="";  

    foreach($checkbox1 as $chk1)  

      {  

if($chk == "")

    {

       $chk .= $chk1;

    }

else{

       $chk .= ",".$chk1;  

     }  

      }  

            $res = $con->query("insert into tblregistration(RegFullName,RegEmail,RegPassword,RegGender,RegHobbies,RegProfile) values('".$_POST["txtfname"]."','".$_POST["txtuemail"]."','".$_POST["txtpassword"]."','".$_POST["rdogender"]."','".$chk."','".$image."')") or die(mysqli_error($con));

            if($res == TRUE)

            {

                echo "<script>alert('Data added successfully..!!')</script>";

            }

            else

            {

                echo "<script>alert('Something getting wrong.Please try again..!')</script>";

            }

        }

/* Insert Code End */

    ?>

</body>

</html>

Step 2. Now run registration.php file into browser. Write http://localhost/foldername/registration.php in browser. Page may look like.

Step 3. Now fill up all the detail of form and click on Insert button to insert data into database and you will see one popup Data added successfully..!! Click on Ok button to close message. Insert code located into registration.php file.

Note: Please read all the comments I have mentioned in code so you can easily understand the code.

Select Operation

Step 1. To display data you have to create one more page and also save that page into folder you created into xampp or wamp and save that page with .php extension. I created display.php page.

display.php

<?php

    $con = new mysqli("localhost","root","","sample");   /* Connection code(Connect with database) */

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Display Data</title>

    <style>

        body{

            margin: 10% auto 0;

        }

        td{

            text-align: center;

        }

    </style>

</head>

<body>

    <center><h1>Display Data Registration</h1></center>

    <table align="center" border="1">

        <tr>

            <th>Full Name</th>

            <th>Email Address</th>

            <th>Gender</th>

            <th>Hobbies</th>

            <th>Profile Picture</th>

            <th>Action</th>

        </tr>

          

        <?php

/* Fetch data from databse(select query) */

            $res = $con->query("select * from tblregistration") or die(mysqli_error($con));

            while($row = mysqli_fetch_array($res))

            {

        ?>

        <tr>

            <td><?php echo $row["RegFullName"]; ?></td>

            <td><?php echo $row["RegEmail"]; ?></td>

            <td><?php echo $row["RegGender"]; ?></td>

            <td><?php echo $row["RegHobbies"]; ?></td>

            <td><img src="images/<?php echo $row["RegProfile"]; ?>" height="100" width="100" alt="User image"></td>

            <td><a href="registration.php?isEdit=<?php echo $row["RegId"]; ?>">Edit</a> | <a href="?delete=<?php echo $row["RegId"]; ?>">Delete</a></td>

        </tr>

        <?php

            }

        ?>

    </table>

    

    <?php

/* Delete code.Wehen click on delete link this will perform.!*/

        if(isset($_REQUEST["delete"]))

        {

            $result=$con->query("select RegProfile from tblregistration where RegId='".$_REQUEST["delete"]."'") or die(mysqli_error($con));

            while($row1=mysqli_fetch_array($result))

            {

                $image1=$row1["RegProfile"];

            }

            unlink("images//".$image1);

            $con->query("delete from tblregistration where RegId='".$_REQUEST["delete"]."'") or die(mysqli_error($con));

            echo "<script>alert('Data deleted successfully..!');window.location='display.php';</script>";   

        }

    ?>

</body>

</html>

Step 2. Now run display.php file into browser. Write http://localhost/foldername/display.php in browser. Page may look like.

Update Operation

Step 1. As you see two links of edit and delete in above image. Click on edit link to perform update operation. When you click on edit link it will redirect to registration.php page with querystring isEdit. isEdit will store RegId of the record on which you have clicked.

On registration.php page all the data has been shown as per RegId on which you have clicked. RegId has been taken from querystring. i.e ?isEdit=1. Page may look like.

Step 2. Now here you can see all the data filled up on form and there are two options Update and Cancel.

Note: If you click on Cancel button then it will redirect to display.php page without performing anything. If you want to update data then change detail filled up on form then click on Update button. You will see one popup Data updated successfully..!! Click on Ok button it will redirect to display.php page and you can see the changes done by you. Update code located in registration.php file.

Delete Operation

Step 1. Click on delete link to perform delete operation. In delete we don’t need to move on any pages, delete code written into display page. When you click on delet link it will use querystring isDelete. isDelete will store RegId of the record on which you have clicked.

When you clicked on delete link it will saw one popup Data deleted successfully..!! Click on Ok button. After click on ok button page redirect to display.php page and you can see the changes made by you.

I hope guys you like my blog. If you have any query please comment it below. Thank you..!!