doumao8355 2015-10-17 01:57
浏览 37
已采纳

有没有办法将单个mysql表转储到只使用php的文件?

I have no access to the command line to use mysqldump. But I have full access to the tables and I can read all data from every table. The problem is I need to save this data into a file on server but only way I can do it is by file_put_contents or similar php function and use some kind of standard mysql dump format to preserve table structure, that is full create string and data types, especially whether particular cell is empty string or NULL. I found this way: https://dev.mysql.com/doc/refman/5.1/en/select-into.html

But using this query:

"SELECT * INTO OUTFILE 'file.txt' FROM $tbl_name"

Gives out this error:

Access denied for user '***'@'***' (using password: YES) [1045]

Ok but I can access all data in that table, so is it possible to iterate all rows and create output file using PHP functions that have in my case permission to write into server disk ? But then do I must to reinvent the wheel and recreate *.sql dump format or is there a way to redirect output from sql command above to a variable in php and then create out file line-by-line ?

  • 写回答

3条回答 默认 最新

  • douji2520 2015-10-17 02:26
    关注

    Here's what I was able to create for a PHP "dump" script.

    Now revised and tested. This will export the following syntax:

    • DROP TABLE IF EXISTS
    • CREATE TABLE
    • ALTER TABLE ADD FOREIGN KEY
    • INSERT INTO TABLE

    Here's the script:

    <?php
    $host = "localhost";
    $username = "usr";
    $password = "pwd";
    $dbname = "my_db";
    $table_name = ""; // If set, dumps only the specified table, otherwise dumps all
    $file = "dump.sql";
    
    
    $mysqli = new mysqli($host, $username, $password, $dbname);
    
    // Get a list of tables
    $sql = "SELECT TABLE_NAME AS `name` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{$dbname}'";
    if ($table_name) {
        $sql .= " AND TABLE_NAME = '{$table_name}'";
    }
    $db_result = $mysqli->query($sql);
    
    $out = "";
    
    // For each table
    while ($table = $db_result->fetch_assoc()) {
        // Build the table
        $sql = "SHOW CREATE TABLE `{$dbname}`.`{$table['name']}`";
        $table_result = $mysqli->query($sql);
        if ($create_table = $table_result->fetch_assoc()) {
            // Build the DROP TABLE DDL
            $out .= "DROP TABLE IF EXISTS `{$dbname}`.`{$table['name']}`;
    
    ";
    
            // Build the CREATE TABLE DDL
            $out .= $create_table['Create Table'] . ";
    
    ";
    
            // Build the FOREIGN KEY DDL for the table
            $sql = "SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = '{$table['name']}' AND CONSTRAINT_SCHEMA = '{$dbname}' AND CONSTRAINT_NAME != 'PRIMARY'";
            $fk_result = $mysqli->query($sql);
            while ($fk = $fk_result->fetch_assoc()) {
                if ($fk['REFERENCED_COLUMN_NAME']) {
                    $out .= "ALTER TABLE `{$dbname}`.`{$fk['TABLE_NAME']}` ADD CONSTRAINT `{$fk['CONSTRAINT_NAME']}` FOREIGN KEY (`{$fk['COLUMN_NAME']}`) REFERENCES `{$fk['REFERENCED_TABLE_NAME']}` (`{$fk['REFERENCED_COLUMN_NAME']}`);
    ";
                }
            }
            $fk_result->close();
            $out .= "
    ";
    
            // Build the INSERT DML for the table
            $sql = "SELECT * FROM `{$table['name']}`";
            $data_result = $mysqli->query($sql);
            while ($row = $data_result->fetch_assoc()) {
                $keys = array_keys($row);
                array_walk($keys, function(&$key) {
                    $key = "`{$key}`";
                });
                $keys = implode(", ", $keys);
                $values = array_values($row);
                array_walk($values, function(&$val) {
                    $val = "'{$val}'";
                });
                $values = implode(", ", $values);
                $out .= "INSERT INTO `{$dbname}`.`{$table['name']}` ({$keys}) VALUES ({$values});
    ";
            }
            $data_result->close();
            $out .= "
    ";
        }
        $table_result->close();
    
    }
    
    $db_result->close();
    file_put_contents($file, $out);
    

    Here's example output for a single-table dump in my DB I tested on:

    DROP TABLE IF EXISTS `user_group`;
    
    CREATE TABLE `user_group` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `type_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `name` varchar(255) NOT NULL,
      `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
    
    ALTER TABLE `user_group` ADD CONSTRAINT `user_group_ibfk_1` FOREIGN KEY (`type_id`) REFERENCES `user_group_type` (`id`);
    
    INSERT INTO `user_group` (`id`, `type_id`, `name`, `created`) VALUES ('1', '1', 'Administrator', '2011-10-01 22:58:29');
    INSERT INTO `user_group` (`id`, `type_id`, `name`, `created`) VALUES ('2', '1', 'Moderator', '2011-10-01 22:58:29');
    INSERT INTO `user_group` (`id`, `type_id`, `name`, `created`) VALUES ('3', '1', 'Registered User', '2011-10-01 22:58:29');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装