|
|
Database Backup using php - PHP
|
Views : 172
|
|
Tagged in : PHP
|
|
|
Report This Scrap as Inappropriate We request you to choose the appropriate categroy and subcategory that suits your
objectionable concern about the scrap, So that our team can review and find out whether it violates our Guidelines or the
scrap is not suitable for all viewers.
|
Export Db backup
error_reporting(E_ALL & ~E_NOTICE);
$hostname="localhost";
$username="root";
$password="";
$dbname="testdb";
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
$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');
?>
|
|
By Jayanthi, On - 2011-12-27 |
|
|
|