php导出mysql

127 篇文章 0 订阅

 <?php
/**
 * @author 至尊王者
 * @author Link http://home.cnblogs.com/u/flying_bat/
 * @developer Zjmainstay
 * @developer Link http://www.zjmainstay.cn
 * @usage
 * MysqlDump::dbDump('localhost', 'zjmainstay', '', 'test', 't_trade', 'tmp.sql');
 */
class MysqlDump {
    /**
     * 数据库内容导出
     * @param $host         database host
     * @param $user         username
     * @param $pwd          password
     * @param $db           database name
     * @param $table        only dump one table
     * @param $filename     custom file to write output content
     */
    public static function dbDump($host, $user, $pwd, $db, $table = null, $filename = null) {
        $mysqlconlink = mysql_connect($host, $user, $pwd, true);
        if (!$mysqlconlink)
            echo sprintf('No MySQL connection: %s',mysql_error())."<br/>";
        mysql_set_charset( 'utf8', $mysqlconlink );
        $mysqldblink = mysql_select_db($db,$mysqlconlink);
        if (!$mysqldblink)
            echo sprintf('No MySQL connection to database: %s',mysql_error())."<br/>";
        $tabelstobackup = array();
        $result = mysql_query("SHOW TABLES FROM `$db`");
        if (!$result)
            echo sprintf('Database error %1$s for query %2$s', mysql_error(), "SHOW TABLE STATUS FROM `$db`;")."<br/>";
        while ($data = mysql_fetch_row($result)) {
            if(empty($table)) {
                $tabelstobackup[] = $data[0];
            } else if(strtolower($data[0]) == strtolower($table)){  //only dump one table
                $tabelstobackup[] = $data[0];
                break;
            }
        }
        if (count($tabelstobackup)>0) {
            $result=mysql_query("SHOW TABLE STATUS FROM `$db`");
            if (!$result)
                echo sprintf('Database error %1$s for query %2$s', mysql_error(), "SHOW TABLE STATUS FROM `$db`;")."<br/>";
            while ($data = mysql_fetch_assoc($result)) {
                $status[$data['Name']]=$data;
            }
            if(!isset($filename)) {
                $date = date('YmdHis');
                $filename = "{$db}.{$date}.sql";
            }
            if ($file = fopen($filename, 'wb')) {
                fwrite($file, "-- ---------------------------------------------------------\n");
                fwrite($file, "-- Database Name: $db\n");
                if(empty($table)) {    //if not only dump single table, dump database create sql 
                    self::_db_dump_create_database($db, $file);
                }
                fwrite($file, "-- ---------------------------------------------------------\n\n");
                fwrite($file, "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n");
                fwrite($file, "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n");
                fwrite($file, "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n");
                fwrite($file, "/*!40101 SET NAMES '".mysql_client_encoding()."' */;\n");
                fwrite($file, "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n");
                fwrite($file, "/*!40103 SET TIME_ZONE='".mysql_result(mysql_query("SELECT @@time_zone"),0)."' */;\n");
                fwrite($file, "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n");
                fwrite($file, "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n");
                fwrite($file, "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n");
                fwrite($file, "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n\n");
                foreach($tabelstobackup as $table) {
                    echo sprintf('Dump database table "%s"',$table)."<br/>";
                    self::need_free_memory(($status[$table]['Data_length']+$status[$table]['Index_length'])*3);
                    self::_db_dump_table($table,$status[$table],$file);
                }
                fwrite($file, "\n");
                fwrite($file, "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\n");
                fwrite($file, "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n");
                fwrite($file, "/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n");
                fwrite($file, "/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n");
                fwrite($file, "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n");
                fwrite($file, "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n");
                fwrite($file, "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n");
                fwrite($file, "/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\n");
                fclose($file);
                echo 'Database dump done!'."<br/>";
            } else {
                echo 'Can not create database dump!'."<br/>";
            }
        } else {
            echo 'No tables to dump'."<br/>";
        }
    }

    protected static function _db_dump_create_database($dbname, $file) {
        $sql = "SHOW CREATE DATABASE `".$dbname."`";
        $result=mysql_query($sql);
        if (!$result) {
            echo sprintf('Database error %1$s for query %2$s', mysql_error(), $sql)."<br/>";
            return false;
        }
        $dbstruc=mysql_fetch_assoc($result);
        fwrite($file, str_ireplace('CREATE DATABASE', 'CREATE DATABASE IF NOT EXISTS', $dbstruc['Create Database']).";\n");
        fwrite($file, "USE `{$dbname}`;\n");
    }

    protected static function _db_dump_table($table,$status,$file) {
        fwrite($file, "\n");
        fwrite($file, "--\n");
        fwrite($file, "-- Table structure for table $table\n");
        fwrite($file, "--\n\n");
        fwrite($file, "DROP TABLE IF EXISTS `" . $table .  "`;\n");
        fwrite($file, "/*!40101 SET @saved_cs_client     = @@character_set_client */;\n");
        fwrite($file, "/*!40101 SET character_set_client = '".mysql_client_encoding()."' */;\n");
        $result=mysql_query("SHOW CREATE TABLE `".$table."`");
        if (!$result) {
            echo sprintf('Database error %1$s for query %2$s', mysql_error(), "SHOW CREATE TABLE `".$table."`")."<br/>";
            return false;
        }
        $tablestruc=mysql_fetch_assoc($result);
        fwrite($file, $tablestruc['Create Table'].";\n");
        fwrite($file, "/*!40101 SET character_set_client = @saved_cs_client */;\n");
        $result=mysql_query("SELECT * FROM `".$table."`");
        if (!$result) {
            echo sprintf('Database error %1$s for query %2$s', mysql_error(), "SELECT * FROM `".$table."`")."<br/>";
            return false;
        }
        fwrite($file, "--\n");
        fwrite($file, "-- Dumping data for table $table\n");
        fwrite($file, "--\n\n");
        if ($status['Engine']=='MyISAM')
            fwrite($file, "/*!40000 ALTER TABLE `".$table."` DISABLE KEYS */;\n");
        while ($data = mysql_fetch_assoc($result)) {
            $keys = array();
            $values = array();
            foreach($data as $key => $value) {
                if($value === NULL)
                    $value = "NULL";
                elseif($value === "" or $value === false)
                    $value = "''";
                elseif(!is_numeric($value))
                    $value = "'".mysql_real_escape_string($value)."'";
                $values[] = $value;
            }
            fwrite($file, "INSERT INTO `".$table."` VALUES ( ".implode(", ",$values)." );\n");
        }
        if ($status['Engine']=='MyISAM')
            fwrite($file, "/*!40000 ALTER TABLE ".$table." ENABLE KEYS */;\n");
    }
    protected static function need_free_memory($memneed) {
        if (!function_exists('memory_get_usage'))
            return;
        $needmemory=@memory_get_usage(true) + self::inbytes($memneed);
        if ($needmemory > self::inbytes(ini_get('memory_limit'))) {
            $newmemory=round($needmemory/1024/1024)+1 .'M';
            if ($needmemory>=1073741824)
                $newmemory=round($needmemory/1024/1024/1024) .'G';
            if ($oldmem=@ini_set('memory_limit', $newmemory))
                echo sprintf('Memory increased from %1$s to %2$s','backwpup',$oldmem,@ini_get('memory_limit'))."<br/>";
            else
                echo sprintf('Can not increase memory limit is %1$s','backwpup',@ini_get('memory_limit'))."<br/>";
        }
    }
    
    protected static function inbytes($value) {
        $multi = strtoupper(substr(trim($value), -1));
        $bytes = abs((int)trim($value));
        if ($multi=='G')
            $bytes=$bytes*1024*1024*1024;
        if ($multi=='M')
            $bytes=$bytes*1024*1024;
        if ($multi=='K')
            $bytes=$bytes*1024;
        return $bytes;
    }
}



MysqlDump::dbDump('localhost', 'root', '', 'sp1');



//导出是正常的,但是用navicat工具导入时有问题,无法看到导入的数据,用cmd命令行导入可以。但要把最上面的一段注释掉:CREATE DATABASE ... USE...




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP可以使用PHPExcel库来导出MySQL数据到Excel。 步骤如下: 1. 首先需要连接MySQL数据库,可以使用mysqli或PDO等扩展库。 2. 查询需要导出的数据,将结果存储到一个数组中。 3. 引入PHPExcel库,创建一个PHPExcel对象。 4. 设置Excel的属性,如标题、作者、描述等。 5. 创建一个工作表,并设置表头。 6. 将查询结果填充到工作表中。 7. 设置Excel的输出格式为Excel2007,并输出Excel文件。 示例代码如下: ```php //连接MySQL数据库 $conn = mysqli_connect("localhost", "username", "password", "database"); //查询需要导出的数据 $sql = "SELECT * FROM table"; $result = mysqli_query($conn, $sql); $data = array(); while ($row = mysqli_fetch_assoc($result)) { $data[] = $row; } //引入PHPExcel库 require_once 'PHPExcel.php'; //创建PHPExcel对象 $objPHPExcel = new PHPExcel(); //设置Excel属性 $objPHPExcel->getProperties()->setTitle("MySQL数据导出")->setCreator("Your Name")->setDescription("MySQL数据导出"); //创建工作表 $objPHPExcel->setActiveSheetIndex(); $objPHPExcel->getActiveSheet()->setTitle("Sheet1"); //设置表头 $objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID'); $objPHPExcel->getActiveSheet()->setCellValue('B1', 'Name'); $objPHPExcel->getActiveSheet()->setCellValue('C1', 'Age'); //填充数据 foreach ($data as $key => $value) { $row = $key + 2; $objPHPExcel->getActiveSheet()->setCellValue('A' . $row, $value['id']); $objPHPExcel->getActiveSheet()->setCellValue('B' . $row, $value['name']); $objPHPExcel->getActiveSheet()->setCellValue('C' . $row, $value['age']); } //设置输出格式为Excel2007 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); //输出Excel文件 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="data.xlsx"'); header('Cache-Control: max-age='); $objWriter->save('php://output'); ``` 以上代码将查询结果导出到Excel文件,并以附件形式下载。可以根据需要修改代码,如更改查询语句、表头等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值