Special Offer - Get $90 Discount and Host Your Dream Web Site @ Dreamhost for 1 Year Click Here. Promo Code SLJ345
Back To Top
Building Impressive Presentations with impress.js
Are you tired of creating boring Presentations?
Take a look at the the future of online presentations with impress.js
in my latest book

How to Clear Database Table Data Using PHP and MySql Truncate

on 2011/05/18 5:01 AM stored in: PHP, SQL and tagged: ,

Why Do We Need to Clear Database Table Data

In production environment we test the web applications by inserting test data to the database tables. Once all the testing is completed we need to install our web application on the real server environment. So we have to remove all test data and install a fresh database. Normally you can do this by exporting a database backup with only the structure without including data from tools like phpMyAdmin or Webmin. But if you have database tables which is used for settings, configurations and pre required data you cannot backup with the above option. Only option you have is to backup tables one by one.

Since this is a difficult task i have provided a script that will delete and clean up all the data from database tables apart from the tables you don’t want to clear.

Empty MySql Table with Truncate Keyword

Sql provides a keyword called truncate which will empty the table contents once used on a specific table. Following code contains the syntax to use truncate.

    mysql_query("truncate table_name");

Clean Up Database Table Data using Mysql Truncate and PHP

Following steps will guide you to use the php clear db script to clear the unwanted table data values from your database.

 

Step 1 – Provide connection details to your mysql server.

 

Step 2 – Specify the name of the database you want to clear.

 

Step 3 – Define the tables you want to preserve data using the $preserve_tables array.

 

Step 4 – Execute the script and it will clear all the data in the tables apart from data in the tables mentioned in $preserve_tables array.

 

/*
*  Connect to Mysql Database
*/
$con=mysql_connect('localhost','username','password');
mysql_select_db('database_name');
/*
*  Get all the tables in the database
*/
$database_tables = mysql_query('show tables');
/*
*  Define the tables to preserve data
*/
$preserve_tables = array('test1');
/*
*  Check the tables to clean up and clear all the data
*/
while($row=mysql_fetch_array($database_tables)){
	$table = trim($row[0]);
	if(!(in_array($table,$preserve_tables))){
		mysql_query("truncate ".$table);
	}
}

 

You may have browsed many websites and spent hours to find the informaion provided in this tutorial. So take 1 minute to share this post to help others find it quickly. Thank You for visiting InnovativePHP.

 

Popular Posts
Recent Posts

 

Comments are closed.

Follow Us On Facebook

Page optimized by WP Minify WordPress Plugin