PHP7.0以上版本备份mysql数据库实操

2022-05-07 建站知识 浏览 手机预览
文章来源:http://www.imtr.cn/html/n263.html
<?php
//php7.0以上版本  备份mysql数据库
/*
//config.php文件
$db_host = '127.0.0.1';//数据库主机地址,通常为:localhos
$db_user = '****';//数据库用户账号
$db_pwd = '***';//数据库用户密码
$db_name = '****';//数据库名称
$db_prefix = 'www_';//数据表前缀
$db_language = 'utf8';//数据库编码
@$con = mysqli_connect($db_host,$db_user,$db_pwd,$db_name);
if(!$con){
$emsg = "<div id='im1'></div><style type='text/css'> #im1{background-image:url(/style/img/mysql_sorry.png);width:900px;height:350px;margin:100px auto 0;}</style>"; 
echo $emsg;
exit();
}
mysqli_set_charset($con,$db_language);//设置数据库编码
*/
require_once(dirname(__FILE__)."/config.php");//引入数据库链接文件
$tables = '*';
backup_tables($db_host, $db_user, $db_pwd, $db_name, $tables);
function backup_tables($host, $user, $pass, $db_name, $tables = '*') {
    $con = mysqli_connect($host,$user,$pass, $db_name);
    mysqli_query($con, "SET NAMES ".$db_language);
    if($tables == '*')
    {
        $tables = array();
        $result = mysqli_query($con, 'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }
    $return = '';
    foreach($tables as $table)
    {
        $result = mysqli_query($con, 'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $num_rows = mysqli_num_rows($result);
        $return.= 'DROP TABLE IF EXISTS '.$table.';';
        $row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
        $counter = 1;
        for ($i = 0; $i < $num_fields; $i++) 
        {
            while($row = mysqli_fetch_row($result))
            {   
                if($counter == 1){
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                } else{
                    $return.= '(';
                }
                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.= ','; }
                }
                if($num_rows == $counter){
                    $return.= ");\n";
                } else{
                    $return.= "),\n";
                }
                ++$counter;
            }
        }
        $return.="\n\n\n";
    }
    $fileName = "backup/".date("Y-m-d_His").'.sql';//保存路径和文件命名
    $handle = fopen($fileName,'w+');
    fwrite($handle,$return);
    if(fclose($handle)){
        echo "备份完成";
        exit();
    }
}


原文地址:http://www.imtr.cn/html/n263.html
  • 如果你的问题还没有解决,可以点击页面右侧的“ ”,站长收到问题后会尽快回复解决方案到你的邮箱。
  • 创造始于问题,有了问题才会思考,有了思考,才有解决问题的方法,才有找到独立思路的可能。 —— 陶行知