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.


/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
	$link = mysql_connect($host,$user,$pass);
	//get all of the tables
	if($tables == '*')
		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result))
			$tables[] = $row[0];
		$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.= "nn".$row2[1].";nn";
		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";
	//save file
	$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');

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!

About the author

PHP | MVC | Codeignitor | Zend | Yii | Smarty | Android | Laravel Expert Senior Software Developer.I love my job and feel happy to working on new ideas and technologies.

Leave a Comment

Comment (required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Name (required)
Email (required)