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

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮