PHPProgramming

Crud Operation in PHP

In this article, I will guide you about crud operation in PHP. We will do create, read, update and delete, we will step by step guide to do crud operation in PHP.

To do the crud operation in PHP we will follow below steps -:

  • Create Database
  • Connection establish with database
  • Create a listing file
  • Insert the Data
  • Edit the data
  • Update the data
  • Delete the data
  • Test the code

Step: 1 Create Database

To create the database you will have to go to your phpmyadmin create a database named as operate_crud after that create a table named as users, users table will contain following columns Id, name, roll, and email where Id will be our primary key.

phpmyadmin database table

Step : 2 Create a database connection.

To create a database connection we will write the following code.

Go to your htdocs, create a folder named as learn-php and under that folder create a file named as db.php and add the below code into it.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $database = "operate_crud";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);

?>

Step:3 Create a Listing File

Now we will create a listing file,where we will show all data which is stored in our database, so in your learn-php folder create a file named as index.php and add the below code into it.

<?php
  session_start();
  include_once 'db.php';
  $result = mysqli_query($conn,"SELECT * FROM users");
  $arrayresult = $result->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="container">
    <h2>Basic Table</h2>
      <?php if (isset($_SESSION['success_message']) && !empty($_SESSION['success_message'])) { ?>
                          <div class="success-message" style="margin-bottom: 20px;font-size: 20px;color: green;">
                                <?php echo $_SESSION['success_message']; ?>
                          </div>
                          <?php
                          unset($_SESSION['success_message']); }
                          ?>
    <a href="create.php" class="btn btn-primary">Create</a>           
    <table class="table table-striped table-borderless table-hover">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Role</th>
          <th>Email</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
       <?php foreach($arrayresult as $key => $abhjeet) { ?>
        <tr>
          <td><?php echo $key ?></td>
          <td><?php echo $abhjeet['name'] ?></td>
          <td><?php echo $abhjeet['role'] ?></td>
          <td><?php echo $abhjeet['email'] ?></td>
          <td><a href="edit.php?id=<?php echo $abhjeet["id"]; ?>" class="btn btn-primary">Edit</a></td>
          <td><a onClick="return confirm('Are You Sure Do You Want To Delete This account?')" href="delete.php?id=<?php echo $abhjeet["id"]; ?>"  class="btn btn-danger">Delete Account</a></td>
        </tr>
        <?php } ?>
      </tbody>
    </table>
  </div>
</body>
</html>

Step: 4 Insert the Data

Now we will insert the data in our database, to insert the data we will create two file, one file for the form as create.php and another as create_submit.php.

Write the below code in your create.php file

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container ">
     <h2> Fill the Form </h2>
       <div class="row ">
         <div class="col-6 col-sm-3">
            <form action="create_submit.php" method="post">
            
                <div class="form-group">
                    <label for="email">Name:</label>
                    <input type="text" class="form-control" name="name"/>
                </div>
                <div class="form-group">
                    <label for="email">Role:</label>
                    <input type="text" class="form-control" name="role"/>
                </div>
                <div class="form-group">
                    <label for="email">Email address:</label>
                    <input type="email" class="form-control" name="email"/>
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>
           </div>
        </div>
    </div>
</body>
</html>

To insert the data in our database write the below code in your create_submit.php file.

<?php
   include 'db.php';
   if (isset($_POST['name'])) {
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $role = mysqli_real_escape_string($conn, $_POST['role']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
      // insert query
      $sql = "INSERT INTO users(name, role,email) VALUES ('$name','$role','$email')";
         if(mysqli_query($conn, $sql)) {
            session_start();
            $_SESSION['success_message'] = "Contact form saved successfully.";
            header("Location: index.php");
            exit();
         } else {
            echo "Server problem, Try after sometime.";
         }
      }
?>

Step: 5 Edit the data

To edit the data,we will create a file named as edit.php, write the below code in your edit.php file.

<?php
include'db.php';
$result = mysqli_query($conn,"SELECT * FROM users WHERE id='" . $_GET['id'] . "'");
$row= mysqli_fetch_array($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <form action="update.php" method="post">
            <input type  ="hidden" name="id" value = "<?php echo $_GET['id'] ?>">
            <div class="form-group">
                <label for="email">Name:</label>
                <input type="text" class="form-control" name="name" id="email" value="<?php echo $row['name']?>">
            </div>
            <div class="form-group">
                <label for="email">Email:</label>
                <input type="email" class="form-control" name="email" id="email" value="<?php echo $row['email']?>" >
            </div>
            <div class="form-group">
                <label for="email">Role:</label>
                <input type="text" class="form-control" name="role" id="email" value="<?php echo $row['role']?>">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
    </div>
</body>

Step: 6 Update the data

To update the data we will create a file named as update.php add the below code in your update.php file.

<?php
include_once('db.php');
mysqli_query($conn,"UPDATE users set name='" . $_POST['name'] . "' ,email='" . $_POST['email'] . "',role='" . $_POST        ['role'] . "' WHERE id='" . $_POST['id'] . "'");
    
if (isset($_POST['name'])) {
    session_start();
    $_SESSION['success_message'] = "Contact form update successfully.";
    header("Location: index.php");
    exit();
} else {
   echo "Server problem, Try after sometime.";
}
?>

Step:7 Now we will delete the data

To delete the data create a file named delete.php and add the below code into it.

<?php
    include 'db.php';
    $sql = "DELETE FROM users WHERE id='" . $_GET['id'] . "'";
    $conn->query($sql);

    session_start();
    $_SESSION['success_message'] = "Contact form successfully Deleted!!!.";
    header("Location: index.php");
?>

Step: 8 Test the code

Now we will test the whole code, is this working fine or not. To test the code visit the URL http://localhost/learn-php/ on in your browser.

listing page crud operation

Now click on create to insert the data into it.

Entet some data in your form and click on submit.

Now it will come to index page after submisson.

Now we will edit the page, click on edit.

edit.php file crud opertion in php

Change the data and click on submit to update the page.

update file in crud operation in php

Now we will delete the data,click on the delete button to delete the data.

Click on the ok to perform the delete operation and click on cancel to reject the delete operation.

Read Also: Remove all zero from the number php

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button