Skip to main content

Backup Your MySQL Database Using PHP

One of the most important tasks any developer needs to do often is back up their MySQL database. In many cases, the database is what drives most of the site. While most web hosts do a daily backup of a customer's database, relying on them to make backups and provide them at no cost is risky to say the least. That's why I've created a database backup function that I can call whenever I want -- including nightly CRONs.

The PHP & MySQL Code

backup_tables('localhost','username','password','blog');


/* 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);
}
Of course, you'll need to provide database credentials to the function, as well as an array of tables you'd like to backup. If you provide a "*" or no tables, a complete database backup will run. The script does the rest!
Never take chances when your website is on the line. Make frequent backups or pay the price later!

Comments

Popular posts from this blog

October CMS E-Commerce Tutorial: GoT White Walkers Protection Store

As many of you probably know, Game of Thrones Season 6 is starting next April 24th. Now I recently introduced myself on this blog , but forgot to mention that I'm, like millions of others, a shameless GoT fan . When our content guy asked me to craft a post showing how the easy e-commerce integration we brag about would work with October CMS, I immediately picked GoT as a theme for the demo. ​ So in this post, I'm going to show you how to set up a store selling defense against the imminent White Walkers invasion. Because WINTER IS COMING big time, you know. ​ ​ More specifically, I'll provide a step-by-step e-commerce tutorial explaining how to integrate our shopping cart platform to an October CMS site. Let's get into it. ​ What is October CMS ​ We've been hearing about October CMS from developers here and there for a while now. This free, open-source CMS platform is the brainchild of fellow Canadian Alexey Bobkov and Australian Samuel Georges. It...

Sublime vs Dreamweaver

13 REASONS TO USE OF SUBLIME TEXT OVER DREAMWEAVER 17 MARCH, 2014 BY TOM ELLIOTT I started writing this post over a year ago but back then it was entitled something along the lines of ‘Reasons why I use Dreamweaver over code editors’. This was biased, as I hadn’t properly explored other code editors like Coda, Sublime Text or Notepad++. So, wanting to write an objective post from a web developers point of view, and because I had heard many good things about it, I setup Sublime Text 2 and dove straight in. I’m glad I did because it quickly became obvious that my presumed reasons for Dreamweaver’s superiority were just wrong. We are all creatures of habit to a greater or lesser degree and when we develop workflows to help make our lives easier, we can get entrenched in the view that these honed practices are superior. It’s not our fault, confirmation bias is supposedly  programmed in our DNA . Even so, it’s healthy to try and keep questioning and challenging ourselves, espe...

JazzCash Mobile Account

  JazzCash Mobile Account Help Center  > JazzCash Mobile Account What is JazzCash mobile account? JazzCash Mobile Account is an actual bank account that is tagged with your mobile number and can be operated through your phone. Through this Mobile Account you can enjoy complete freedom of accessing financial services anywhere, anytime! More importantly, you don’t have to rely on traveling to a Bank branch, wait at queues or complete any documentation. Mobile Account menu works on all types of mobile phones – smart phone is not required. Customers can make deposits or withdrawals through any Mobilink Microfinance Bank Branch, Mobilink Franchise, Mobilink Business Center and Jazzcash Agents spread across Pakistan. JazzCash Mobile App In line with the continuous digitization of its services to meet demands of growing number of smartphone users, JazzCash is proud to announce Android based App for its Mobile Account users. The App offers a user friendly inte...