رتبه موضوع:
  • 0 رای - 0 میانگین
  • 1
  • 2
  • 3
  • 4
  • 5
Backup گرفتن از دیتابیس
#1
<?php
    function backup_db($host, $user, $pass, $name, $tables = '*') {
        date_default_timezone_set('Asia/Tehran');
  
        $return = '';
  
        mysql_connect($host,$user,$pass) or die('Connection error');
        mysql_select_db($name) or die('Database error');
        mysql_query('SET NAMES 'utf8'');
        mysql_set_charset('utf8');
  
        if($tables == '*') {
            $tables = array();
            $result = mysql_query('SHOW TABLES');
            while($row = mysql_fetch_row($result)) {
                $tables[] = $row[0];
            }
            mysql_free_result($result);
        }
        else {
            $tables = is_array($tables) ? $tables : explode(',', $tables);
        }
  
        foreach($tables as $table) {
            $result = mysql_query('SELECT * FROM `'.$table.'`');
            $num_fields = mysql_num_fields($result);
            $return .= 'DROP TABLE IF EXISTS `'.$table.'`;'.PHP_EOL.PHP_EOL;
            $row = mysql_fetch_row(mysql_query('SHOW CREATE TABLE `'.$table.'`'));
            $return .= $row[1].';'.PHP_EOL.PHP_EOL;
  
            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] = str_replace('n', '\n', $row[$j]);
                        if (isset($row[$j])) {
                            $return .= '''.$row[$j].''';
                        }
                        else {
                            $return .= '''';
                        }
                        if ($j < ($num_fields - 1)) {
                            $return .= ',';
                        }
                    }
                    $return .= ');'.PHP_EOL;
                }
            }
            $return .= PHP_EOL.PHP_EOL.PHP_EOL;
        }
          
        $handle = fopen('db-backup-'.$name.'-'.date('Y,m,d-H,i,s').'.sql', 'w');
        fwrite($handle, $return);
        fclose($handle);
    }
?>

مثالی از نحوه استفاده:

backup_db('localhost', 'root', '', 'your_db_name');
پاسخ
تشکر شده توسط: php




کاربران در حال بازدید این موضوع: 1 مهمان