[php] Clear data in MySQL table with PHP?

How do I clear all the entries from just one table in MySQL with PHP?

This question is related to php mysql

The answer is


TRUNCATE TABLE mytable

Be careful with it though.


TRUNCATE TABLE tablename

or

DELETE FROM tablename

The first one is usually the better choice, as DELETE FROM is slow on InnoDB.

Actually, wasn't this already answered in your other question?


TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.

we can use for truncate

TRUNCATE TABLE tablename

we can use for delete

DELETE FROM tablename

we can also give conditions as below

DELETE FROM tablename WHERE id='xyz'


TRUNCATE TABLE table;

is the SQL command. In PHP, you'd use:

mysql_query('TRUNCATE TABLE table;');

Actually I believe the MySQL optimizer carries out a TRUNCATE when you DELETE all rows.


MySQLI example where $con is the database connection variable and table name is: mytable.

mysqli_query($con,'TRUNCATE TABLE mytable');

TRUNCATE TABLE `table`

unless you need to preserve the current value of the AUTO_INCREMENT sequence, in which case you'd probably prefer

DELETE FROM `table`

though if the time of the operation matters, saving the AUTO_INCREMENT value, truncating the table, and then restoring the value using

ALTER TABLE `table` AUTO_INCREMENT = value

will happen a lot faster.