Skip to content

Instantly share code, notes, and snippets.

@1stevengrant
Created August 9, 2010 09:00
Show Gist options
  • Save 1stevengrant/515170 to your computer and use it in GitHub Desktop.
Save 1stevengrant/515170 to your computer and use it in GitHub Desktop.
<?php
/* fill in your database name */
$database_name = "dbname";
/* connect to MySQL */
if (!$link = mysql_connect("dbservername", "dbuser", "dbuserpass")) {
die("Could not connect: " . mysql_error());
}
/* query all tables */
$sql = "SHOW TABLES FROM $database_name";
if($result = mysql_query($sql)){
/* add table name to array */
while($row = mysql_fetch_row($result)){
$found_tables[]=$row[0];
}
}
else{
die("Error, could not list tables. MySQL Error: " . mysql_error());
}
/* loop through and drop each table */
foreach($found_tables as $table_name){
$sql = "DROP TABLE $database_name.$table_name";
if($result = mysql_query($sql)){
echo "Success - table $table_name deleted.";
}
else{
echo "Error deleting $table_name. MySQL Error: " . mysql_error() . "";
}
}
/* restore the tables from sql file */
// Name of the file
$filename = '/pathtofile/db.sql';
// MySQL host
$mysql_host = 'dbservername';
// MySQL username
$mysql_username = 'dbuser';
// MySQL password
$mysql_password = 'dbuserpass';
// Database name
$mysql_database = 'dbname';
//////////////////////////////////////////////////////////////////////////////////////////////
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line_num => $line) {
// Only continue if it's not a comment
if (substr($line, 0, 2) != '--' && $line != '') {
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
// Perform the query
mysql_query($templine) or print('Error performing query \'<b>' . $templine . '</b>\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment