Drop Multiple MySQL Tables
2008-10-14 21:02:10
Category: php:database
Description: Connect to a MySQL database, match tables against a regular expression and delete the matches.
Author: detour
Viewed: 1794
Rating: (6 votes)


<?php
// delete-tables.php by detour@metalshell.com
//
// Drop multiple tables in mysql, matched by a regular expression.
//
// http://www.metalshell.com/
//
 
// Settings
$match_str = '/.*ChangeToWhatever.*/i';
 
$dbuser = 'user';
$dbpass = 'pass';
$dbname = 'database';
$dbhost = 'localhost';
//////////////////////////
 
 
 
if(isset($_SERVER['REQUEST_URI'])) die("Run from command line, not from browser.");
 
$db = mysql_connect($dbhost, $dbuser, $dbpass) or die("Error Connecting to DB.\n");
$dbsel = mysql_select_db($dbname, $db) or die("Unable to select `$dbname`\n");
 
$drop_tables = array();
// Get list of tables
$res = mysql_query("SHOW TABLES FROM `$dbname`");
while(($row = mysql_fetch_array($res))) {
  if(preg_match($match_str, $row[0])) $drop_tables[] = $row[0];
}
 
if(count($drop_tables)) {
  echo "The following tables will be deleted.\n";
  foreach($drop_tables as $value) {
    echo $value . "\n";
  }
 
  echo "\n\n\nThese tables will be deleted in 10 seconds, ctrl-c to cancel\n";
  sleep(10);
 
  foreach($drop_tables as $value) {
    mysql_query("DROP TABLE `$value`");
  }
 
  echo count($drop_tables) . " tables deleted.\n";
} else {
  echo "No tables matched.\n";
}
 
mysql_close($db);