Insertion and Deletion of data using PHP

In MySQL database we can we can perform creation, insertion and deletion of data with the help of CRUD operations ( Create, Read, Upload, Delete ). Now Lets see the example :

create.php
<?php

  $server = "localhost";
  $username = "root";
  $password = "";

  $connection = mysqli_connect($server, $username, $password);

  // Creating database
  $sql = "CREATE DATABASE mydb";
  if(mysqli_query($connection, $sql)){
    echo "Database createed Successfully.<br/>";
  } else {
    echo "<br/>Error in Executing query : " . mysqli_error($connection);
  }

  // Select the newly created database
  mysqli_select_db($connection, "mydb");


  // Creating table
  $sql = " CREATE TABLE Employee (
             EmpId INT(5),
             EmpName VARCHAR(15),
             Salary INT(7),
             Addr VARCHAR(30),
             PIN INT(6),
             PRIMARY KEY(EmpId)
          );";

  if(mysqli_query($connection, $sql)){
    echo "Table createed Successfully.<br/>";
  } else {
    echo "<br/>Error in Executing query : " . mysqli_error($connection);
  }

  mysqli_close($connection);

?>
Output :

Database created Successfully.
Table created Successfully.

The above given php code create.php, creates the database and the table structure.

insert.php
<?php

  $server = "localhost";
  $username = "root";
  $password = "";
  $dbName = "mydb";

  $connection = mysqli_connect($server, $username, $password, $dbName);

  $sql = " INSERT INTO Employee VALUES 
           (101, 'John', 2000, 'Boston', 300987), 
           (102, 'Mary', 3000, 'Chicago', 788067),
           (103, 'Sam', 5000, 'NewYark', 564908),
           (104, 'Bruce', 8000, 'Gothum', 124323),
           (105, 'Clark Kent', 1500, 'NewYark', 564908),
           (106, 'Jack', 2000, 'Russia', 123456)";

  if(mysqli_query($connection, $sql)) {
    echo "Table data inserted successfully.";
  } else {
    echo "<br/>Error in Executing query : " . mysqli_error($connection);
  }

  mysqli_close($connection);

?>
Output :

Table data inserted successfully.

The above given php code insert.php, inserts the six rows of data into the employee table, which we are created previously.

delete.php
<?php

  $server = "localhost";
  $username = "root";
  $password = "";
  $dbName = "mydb";

  $connection = mysqli_connect($server, $username, $password, $dbName);

  $sql = "DELETE FROM employee WHERE EmpId = 106";

  if(mysqli_query($connection, $sql)) {
    echo "Data Deleted successfully.";
  } else {
    echo "<br/>Error in Executing query : " . mysqli_error($connection);
  }

  mysqli_close($connection);

?>
Output :

Data Deleted successfully.

The above given php code delete.php, deletes an employee data, which empId is 106.

Next Topic :