Sunday, December 7, 2008

MUST READ! If you have been screwed over, here is how to backup your entire database

Within the past few hours I have been messing around with JoomlaPC and I noticed something, it was grabbing my articles, site and everything from the database. But the database I could not find. The local phpmyadmin program I had installed on my machine locally contained sample data. Then I looked at my configuration file and noticed that it was grabbing the database from Siteground.

They actually hadn't removed my database. So in a hurry a ran over to Google and found a script that backups your entire database to a file on your computer. With that all setup I ran and it dumped my database to file.

This may be of use for some of you (including those who don't use Joomla). For this script be sure you edit it with your database information but do not but localhost as the connection address, the IP Address you want to put is 67.15.211.3.

Here is the script:

START CODE
backup_tables('67.15.211.3','username','password','databasename');


/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{

$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);

//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}

//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);

$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";

for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}

//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
?>

END CODE

In order to execute this code you have to have JoomlaPC installed on your local PC and then just copy this code into a text document save it as "perform.php" and move it to the Joomla folder (which is inside the WWW folder) and then just access http://localhost/Joomla/perform.php from your web brower and it will dump your entire database to a file called db-backup-[LONG_SERIES_OF_NUMBERS_HERE].sql

This was a miracle to me! So if you have been screwed over there still might be hope!

-Mike

No comments: