ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

13-MySQL Delete Data

In Deleting data using MySQL the DELETE Statement is used.

Syntax:

DELETE FROM tablename
WHERE specificcolumn = correspondingvalue

 

Take Note! Using the DELETE command you must not forget to include the WHERE clause, because the Where clause is used to specify record you want to delete. Without having the WHERE clause, all records in the table will be deleted.

Here the following examples in Deleting record from “tblpeople”.

Example using MySQLi(Object-Oriented):

 

  1. <?php
  2. $server = "localhost";
  3. $username = "root";
  4. $password = "";
  5. $database = "mysqltutorial";
  6.  
  7. // Create connection
  8. $conn = new mysqli($server, $username, $password, $database);
  9. // Check connection
  10. if ($conn->connect_error) {
  11. die("Connection failed: " . $conn->connect_error);
  12. }
  13.  
  14. // sql to delete record from table
  15. $sql = "DELETE FROM tblpeople WHERE ID=9";
  16.  
  17.  
  18. if ($conn->query($sql) === TRUE) {
  19.     echo "Record Delete successfully";
  20. } else {
  21.     echo "Error: " . $sql . "<br>" . $conn->error;
  22. }
  23.  
  24. $conn->close();
  25. ?>

Example using MySQLi(Procedural):

  1. <?php
  2.  
  3. $server = "localhost";
  4. $username = "root";
  5. $password = "";
  6. $database = "mysqltutorial";
  7.  
  8. // Create connection
  9. $conn = mysqli_connect($server, $username, $password, $database);
  10. // Check connection
  11. if (!$conn) {
  12.     die("Connection failed: " . mysqli_connect_error());
  13. }
  14.  
  15. // sql to Delete record from table
  16. $sql = "DELETE FROM tblpeople WHERE ID=9";
  17.  
  18. if (mysqli_query($conn, $sql)) {
  19.    
  20.   echo "Record Delete successfully";
  21. } else {
  22.     echo "Error: " . $sql . "<br>" . mysqli_error($conn);
  23. }
  24.  
  25. mysqli_close($conn);
  26. ?>

Example using PDO:

 

  1. <?php
  2.  
  3. $server = "localhost";
  4. $username = "root";
  5. $password = "";
  6. $database = "mysqltutorial";
  7.  
  8. try {
  9.     $conn = new PDO("mysql:host=$server;dbname=$database", $username, $password);
  10.     // set the PDO error mode to exception
  11.     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  12.  
  13.        
  14.     // sql to Delete record from table
  15.     $sql = "DELETE FROM tblpeople WHERE ID=8";
  16.    
  17.     $conn->exec($sql);
  18.     echo "Record Delete successfully";
  19.     }
  20. catch(PDOException $e)
  21.     {
  22.    
  23.     echo $sql . "<br>" . $e->getMessage();
  24.     }
  25.  
  26. $conn = null;
  27. ?>

 

Facebook Comments

Check Your Domain Ranking

Leave a Reply

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

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!