PHP MySQL CRUD Application with Source Code


In this example we will create a CRUD application with PHP and MySQL. CRUD is an acronym for Create, Read, Update, and Delete. CRUD operation helps to Insert, Select, Update and Delete database records. The following example shows, how to create CRUD application with PHP - MySQL

PHP MySQL CRUD Application with Source Code

Files and Directory

php_mysql_crud/
  ├── config.php
  ├── index.php
  ├── edit.php
  ├── delete.php
  ├── style.css
  ├── db_sample.sql

Download Source Code.

Creating the Database and Table

Execute the following SQL query to create a table named 'users_data' inside your MySQL database named 'db_sample'.

 
CREATE TABLE  users_data (
  UID int(11) NOT NULL AUTO_INCREMENT,
  NAME varchar(150) NOT NULL,
  EMAIL varchar(50) NOT NULL,
  CONTACT varchar(50) NOT NULL,
  PRIMARY KEY (UID)
);
config.php
<?php 
  #Connect Database
  $con=mysqli_connect("localhost","root","","db_sample");
  if(!$con){
    die("Connection Failed ".$con->connect_erro);
  }
  
  #flash message
  function flash($name='',$msg='',$cate='green'){
    if(!empty($name)){
      if(!empty($msg)&&empty($_SESSION[$name])){
        $_SESSION[$name]=$name;
        $_SESSION[$name."_msg"]=$msg;
        $_SESSION[$name."_cate"]=$cate;
      }
      else if(empty($msg)&&!empty($_SESSION[$name])){
        echo "<div class='alert-{$_SESSION[$name."_cate"]}'>{$_SESSION[$name."_msg"]}</div>";
        unset($_SESSION[$name]);
        unset($_SESSION[$name."_msg"]);
        unset($_SESSION[$name."_cate"]);
      }
    }
  }
?>
index.php
<?php
  session_start();
  include "config.php";

  #Check if form submitted
  if($_SERVER["REQUEST_METHOD"]=='POST'){
    $name=mysqli_real_escape_string($con,$_POST["frm_name"]);
    $email=mysqli_real_escape_string($con,$_POST["frm_email"]);
    $contact=mysqli_real_escape_string($con,$_POST["frm_contact"]);
    $sql="INSERT INTO users_data (NAME,EMAIL,CONTACT) VALUES ('{$name}','{$email}','{$contact}')";
    if($con->query($sql)){
      #set flash message
      flash('msg','User Added Successfully');
    }else{
      #set flash message
      flash('msg','User Added Failed','red');
    }
  }

  #select all records from the table
  $data=[];
  $sql="select * from users_data";
  $res=$con->query($sql);
  if($res->num_rows>0){
    while($row=$res->fetch_assoc()){
      $data[]=$row;
    }
  }
?>
<html>
  <head>
    <title>PHP - MySQL CRUD </title>
    <link rel='stylesheet' href='style.css'>
  </head>
  <body>
    <div class='container'>
      <?php 
        #print flash message
        flash('msg'); 
      ?>
      <form method='post' action='<?php echo $_SERVER["PHP_SELF"]; ?>' class='frm'>
        <h1>PHP - MySQL CRUD</h1><hr>
        <div class='group'>
          <label>Name : </label>
          <input type='text' name='frm_name' required>
        </div>
        <div class='group'>
          <label>Email : </label>
          <input type='email' name='frm_email' required>
        </div>
        <div class='group'>
          <label>Contact : </label>
          <input type='text' name='frm_contact' required>
        </div>
        <div class='group'>
          <input type='submit' name='submit' class='btn-green' value='Save Details'>
        </div>
      </form>
      <?php if(count($data)>0){ ?>
          <table>
            <thead>
              <tr>
                <th>SNo</th>
                <th>Name</th>
                <th>Email</th>
                <th>Contact</th>
                <th>Edit</th>
                <th>Delete</th>
              </tr>
            </thead>
            <tbody>
              <?php 
                $i=0; 
                foreach($data as $row){ 
                $i++;
              ?>
              <tr>
                <td><?php echo $i; ?></td>
                <td><?php echo $row["NAME"]; ?></td>
                <td><?php echo $row["EMAIL"]; ?></td>
                <td><?php echo $row["CONTACT"]; ?></td>
                <td><a href='edit.php?id=<?php echo $row["UID"]; ?>' class='btn-blue'>Edit</a></td>
                <td><a href='delete.php?id=<?php echo $row["UID"]; ?>' onclick='return confirm("Are You Sure?")'  class='btn-red'>Delete</a></td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
      <?php }else{ ?>
        <div class='alert-red'>No Records</div>
      <?php }?>
    </div>
  </body>
</html>
edit.php
<?php
  session_start();
  include "config.php";
  
  #Check if form submitted
  $message="";
  if($_SERVER["REQUEST_METHOD"]=='POST'){
    $name=mysqli_real_escape_string($con,$_POST["frm_name"]);
    $email=mysqli_real_escape_string($con,$_POST["frm_email"]);
    $contact=mysqli_real_escape_string($con,$_POST["frm_contact"]);
    $sql="UPDATE users_data SET NAME='{$name}',EMAIL='{$email}',CONTACT='{$contact}' WHERE UID='{$_GET["id"]}'";
    if($con->query($sql)){
      flash('msg','User Updated Successfully');
    }else{
      flash('msg','User Updated Failed','red');
    }
  }
  
  #Select user details from the table
  $sql="select * from users_data where UID='{$_GET["id"]}'";
  $res=$con->query($sql);
  if($res->num_rows>0){
    $row=$res->fetch_assoc();
?>
<html>
  <head>
    <title>PHP - MySQL CRUD </title>
    <link rel='stylesheet' href='style.css'>
  </head>
  <body>
    <div class='container'>
      <?php flash('msg'); ?>
      <form method='post' action='<?php echo $_SERVER["REQUEST_URI"]; ?>' class='frm'>
        <h1>PHP - MySQL CRUD</h1><hr>
        <div class='group'>
          <label>Name : </label>
          <input type='text' name='frm_name' required value="<?php echo $row["NAME"]; ?>">
        </div>
        <div class='group'>
          <label>Email : </label>
          <input type='email' name='frm_email' required value="<?php echo $row["EMAIL"]; ?>">
        </div>
        <div class='group'>
          <label>Contact : </label>
          <input type='text' name='frm_contact' required value="<?php echo $row["CONTACT"]; ?>">
        </div>
        <div class='group'>
          <input type='submit' name='submit' class='btn-green' value='Update Details'>
        </div>
        <a href='index.php'>Back to Home</a>
      </form>
    </div>
  </body>
</html>
<?php 
  }
?>
delete.php
<?php
  session_start();
  include "config.php";
  
  $sql="DELETE FROM users_data WHERE UID='{$_GET["id"]}'";
  if($con->query($sql)){
    flash('msg','User Deleted Successfully');
    header("location:index.php");
  }else{
    flash('msg','User Deleted Failed','red');
    header("location:index.php");
  }
?>
style.css
html,body{
  margin:0;
  padding:0;
  font-family:Cambria;
  font-size:18px;
}
.container{
  padding:5px 20px;
}
.frm{
  width:400px;
  margin:20px auto;
}
.group{
  margin-bottom:15px;
}
.group label{
  display:block;
  margin-bottom:5px;
}
.group input[type='text'],.group input[type='email']{
  width:100%;
  border:none;
  border:1px solid #ccc;
  padding:8px 5px;
}
.btn-green{
  border:none;
  background:#008223;
  border:1px solid #008223;
  color:white;
  padding:10px 15px;
  border-radius:5px;
}
.btn-red{
  border:none;
  background:#cf562d;
  border:1px solid #cf562d;
  color:white;
  padding:2px 15px;
  border-radius:5px;
  text-decoration:none;
  font-size:14px;
}
.btn-blue{
  border:none;
  background:#3a74e8;
  border:1px solid #3a74e8;
  color:white;
  padding:2px 15px;
  border-radius:5px;
  text-decoration:none;
  font-size:14px;
}
.btn-green:hover{
  opacity:0.9;
}
.alert-green{
  width:100%;
  padding:15px 20px;
  background-color:#c8f0c7;
  color:#335232;
  box-sizing:border-box;
}
.alert-red{
  width:100%;
  padding:15px 20px;
  background-color:#f0d2c9;
  color:#735951;
  box-sizing:border-box;
}
table{
  border-collapse:collapse;
  width:100%;
  font-size:17px;
}
table td,table th{
  border:1px solid #ccc;
  padding:10px 8px;
}