Php - Backup mysql database script, Automate export and import mysql database
Backup mysql database script
<?php error_reporting(E_ALL & ~E_NOTICE); $hostname="localhost"; $username="root"; $password="mypass"; $dbname="backupdb"; backup_tables($hosthost,$username,$password,$dbname); 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); } foreach($tables as $table) { $result = mysql_query('SELECT * FROM '.$table); $n_fields = mysql_num_fields($result); $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table)); $return.= "\n\n".$row2[1].";\n\n"; for ($i = 0; $i < $n_fields; $i++) { while($row = mysql_fetch_row($result)) { $return.= 'INSERT INTO '.$table.' VALUES('; for($j=0; $j<$n_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<($n_fields-1)) { $return.= ','; } } $return.= ");\n"; } } $return.="\n\n\n"; } //save file $handle = fopen('db-backup-'.time().'.sql','w+'); //$handle = fopen('backup.sql','w+')or die('canot open'); fwrite($handle,$return); fclose($handle); echo "Backup Database Successfully"; } ?> Import Db backup <?php $db="testing"; $link = mysql_connect('localhost','root',''); mysql_select_db($db,$link); $sql = explode(';', file_get_contents ('backupdb.sql')); //Give filename.sql $n = count ($sql) - 1; for ($i = 0; $i < $n; $i++) { $query = $sql[$i]; $result = mysql_query ($query) or die (' Query: ' . $query . ' failed. MySQL error: ' . mysql_error()); } //unlink('backupdb.sql'); ?>
The topic on Php - Backup mysql database script is posted by - Maha
Hope you have enjoyed, Php - Backup mysql database scriptThanks for your time