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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀