Empty a table in MySQL database with HTML form and PHP

Posted by Shek on May 18, 2008 under PHP | Be the First to Comment | Total View: 16,379 views

Editor’s note: In some cases which the user might need to empty a table in the MySQL database. Instead of deleting every record in the MySQL database, you could run a query “truncate table ‘tablename’” to do the job.

Here I have created a example to show you how to empty a table in MySQL database with HTML form and PHP:

I have created a database with a table named “test” and with 2 fields named “name” and “password”, the 2 fields are both has records in them.
I have created a HTML file called “emptytableform.html” with a HTML form in it.
I have created a php file called “emptytable.php”.

Here are the codes:

For emptytableform.html:

A HTML form with 1 text field named “temptable’ and one submit button create here. User has to input the table name into the “temptable” text field. When the submit button is clicked, the form will direct us to the “emptytable.php” file.

<html>
<form action="emptytable.php" method="post">
Enter the table you like to empty:
<input name="temptable" type="text" />
<input name="Submit" type="submit" value="empty table" />
</form>
</html>

Enter the table you like to empty:

For deletetable.php:

First we have to connect to database:

mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");

Then we create a PHP variable to hold the input from the text field “temptable” of the HTML form.

$temptable = $_POST['temptable'];

Now we create the query for emptying the table which has the name the same as the input from the text field “temptable” of the HTML form:

$query = "truncate table $temptable";

We then run the query with the “mysql_query( )’ PHP function and to check whether the table has emptied successfully, I have put an “if” condition there to echo out the result:

if(mysql_query($query)){
echo "table empty";}
else{
echo "fail";}

All together for emptytable.php:

1
2
3
4
5
6
7
8
9
10
<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$temptable = $_POST['temptable'];
$query = "truncate table $temptable";
if(mysql_query($query)){
echo "table empty";}
else{
echo "fail";}
?>

Similar Posts:

VN:F [1.9.22_1171]
Rating: 6.1/10 (9 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 2 votes)
Empty a table in MySQL database with HTML form and PHP, 6.1 out of 10 based on 9 ratings

Not what you want? Try a Search

Add A Comment

*