Here’s a snippet to backup MySQL database content to SQL file using PHP code. This code is very useful when you want to make a daily or hourly snapshot of your currently running database. Or maybe you want to add a backup feature on your blog CMS.
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);
}
Credits: David Walsh
thanks, this is very usefull
Top Nice Article. Klo koneksinya pakai PDO sdh ada belum?
Thanks nice info verry usefull
Artikel yang sangat menarik min
Sangat menarik nih buat dicoba..
please explain why I always fail backups big database. i search in stackoverflow but nobody can teach me to solve this problem..
Save my time..
Beberapa waktu lalu saya menemukan masalah untuk hal ini, terima kasih sudah berhasil dengan menerapkan cara di atas.. 🙂
Koneksi ke database-nya blm pakai OOp ya ?
Dịch vụ thu mua phế liệu ở đâu giá cao nhất tpHCM. Hãy để Phương Linh trả lời tất cả băn khoăn giúp bạn trong 10 phút nhé.
Thank you for publishing good content
This was an extremely nice post.
Nice one! Thank you for sharing this post.
Nice one! Thank you for sharing this post.
This was an extremely nice post.
Thank you for publishing good content
Thanks for nice post!
nice blog. I like it
Botox injection
create your site in Nonegar
being knuckles to was mirrors he the
we’d breathe of back town. it “That
Quality articles or reviews is the secret to invite the people to pay a visit the web site, that’s what this website is providing.
gacor slot site as an online gambling site agent raja slot gacor hari ini offers you online soccer gambling games with clear score calculations, it’s much easier for you to win