Articles

PHP MySQL - TRUNCATE

PHP MySQL - TRUNCATE


Let’s discuss how to delete all records from a table  in MYSQL through PHP  in the XAMPP Server.

Consider the table - Medicine present in the database - hospital snapshot with existing record.

 

 

TRUNCATE in MySQL is used to delete all the rows from a table but not delete the table schema.

 

SQL TRUNCATE - Syntax

 

TRUNCATE TABLE TABLE_NAME;

Approach:

1.Specify the credentials to create a connection object.
The credentials include XAMPP Server localhost name, username, password and database name.
$connecting_data =  new mysqli($server, $user, $pwd, $data);

2.Specify the SQL Query that includes the TRUNCATE
$my_query = TRUNCATE TABLE TABLE_NAME;

3.Query to check whether ll the records are deleted or not.
if ($connecting_data->query($my_query) === TRUE) {
  echo "Table Truncated Succesfully!!.";
} else {
  echo "Error: " . $connecting_data->error;
};

4.Close the connection object
$connecting_data->close();

Example:

In this example, we will delete all the rows from the Medicine Table using TRUNCATE.

<?php

// Specify the server
$server = "localhost";

// Specify the user
$user = "root";

// Specify the password
$pwd = "";

// Specify the database 
$data = "hospital";

// Let's create connection by using the above details
$connecting_data =  new mysqli($server, $user, $pwd, $data);

$my_query = "TRUNCATE TABLE Medicine";


if ($connecting_data->query($my_query) === TRUE) {
  echo "Medicine Truncated Succesfully!!.";
} else {
  echo "Error: " . $connecting_data->error;
}

$connecting_data->close();
?>

Output:

Let's check in XAMPP:

So, we can see that all the records were deleted but the columns remain same.

 

Conclusion:

In this tutorial, we seen how  to delete all the rows from a table through PHP Script using TRUNCATE in XAMPP Server.

 


PHP MySql

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Gottumukkala Sravan Kumar 171FA07058
B.Tech (Hon's) - IT from Vignan's University. Published 1400+ Technical Articles on Python, R, Swift, Java, C#, LISP, PHP - MySQL and Machine Learning
Page Views :    Published Date : Jun 14,2024  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!