简体   繁体   中英

is there a way to dump single mysql table into a file using only 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 ?

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']}`;\n\n";

        // Build the CREATE TABLE DDL
        $out .= $create_table['Create Table'] . ";\n\n";

        // 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']}`);\n";
            }
        }
        $fk_result->close();
        $out .= "\n";

        // 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});\n";
        }
        $data_result->close();
        $out .= "\n";
    }
    $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');

You can execute a SHOW CREATE TABLE to get the structure and then a SELECT * FROM to get the data. From there you should be able to write the correct output to a file or the HTTP response.

It is also possible the do the dump on the remote machine . So you can start mysqldump on the remote computer and directly store there the file. it then also not necessary to copy them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM