How to drop all tables in database without dropping the database itself?

Viewed 37252

I would like to delete all the tables from database, but not deleting the database itself. Is it possible ? I'm just looking for shorter way than removing the database and create it again. Thanks !

10 Answers

A procedural way to do this is as follows:

$query_disable_checks = 'SET foreign_key_checks = 0';

$query_result = mysqli_query($connect, $query_disable_checks);

// Get the first table
$show_query = 'Show tables';
$query_result = mysqli_query($connect, $show_query);
$row = mysqli_fetch_array($query_result);

while ($row) {
  $query = 'DROP TABLE IF EXISTS ' . $row[0];
  $query_result = mysqli_query($connect, $query);

  // Getting the next table
  $show_query = 'Show tables';
  $query_result = mysqli_query($connect, $show_query);
  $row = mysqli_fetch_array($query_result);
}

Here $connect is just the connection made with mysqli_connect();.

You can execute this. Just add more tables if I missed any

drop table wp_commentmeta;
drop table wp_comments;
drop table wp_links;
drop table wp_options;
drop table wp_postmeta;
drop table wp_posts;
drop table wp_term_relationships;
drop table wp_term_taxonomy;
drop table wp_termmeta;
drop table wp_terms;
drop table wp_usermeta;
drop table wp_users;

The single line query to drop all tables, as below:

$dbConnection = mysqli_connect("hostname", "username", "password", "database_name");
$dbConnection->query('SET foreign_key_checks = 0');

$qry_drop = "DROP TABLE IF EXISTS buildings, business, computer, education, fashion, feelings, food, health, industry, music, nature, people, places, religion, science, sports, transportation, travel";            
$dbConnection->query($qry_drop);

$mysqli->query('SET foreign_key_checks = 1');
$mysqli->close();
Related