Reputation: 5243
I have a backup file (.sql.gz) and I want to import it to my empty database on localhost programmatically like how phpmyadmin does, inside a browser with php/mysql/javascript and not via command line. Since it's my localhost, security is not really a concern, I just want to automate a task I have to perform regularly when developing.
There are a bunch of questions here but they all deal with command line solution.
edit: I already have a xampp installation. But the whole procedure is tedious, I have to first delete the database, then recreate it and then import my data. I have to move b/w previous database backus fairly often. So I want to automate the process. I just give in the backup .sql.gz file via html form input and it does all of the above automatically.
Upvotes: 3
Views: 7567
Reputation: 562358
Comment from @MarcB is correct. Use PHP to call out to a shell process to load the SQL script.
Writing a PHP script to execute a backup script is a waste of time. You basically have to implement the mysql client in PHP.
The better solution is something like this:
shell_exec("gunzip -c $file_sql_gz | mysql --defaults-file=$my_cnf $database_name");
Where $my_cnf
is the name of a my.cnf-like file that contains host, user, password to connect.
See also some of my past answers:
Re your comment:
Refer to http://www.php.net/manual/en/features.file-upload.post-method.php
You can access the temp name of a file upload with $_FILES['userfile']['tmp_name']
.
Upvotes: 1
Reputation: 23777
I'd open it with gzfile
, separate it on the query-delimiter and put it into mysqli::query
$file = implode('', gzfile($sqlFile)); // there doesn't exist a gz* function which reads it completely into a string?
$query = $substring_delimiter = "";
$last_was_backslash = false;
$outside_begin_end = true;
$delimiter = ';';
for ($i = 0; $i < strlen($file); $i++) {
if ($i > 3 && !strcasecmp(substr($file, $i - 4, 5), "BEGIN") && !$substring_delimiter)
$outside_begin_end = false;
if (!$outside_begin_end && !strcasecmp(substr($file, $i - 2, 3), "END") && !$substring_delimiter)
$outside_begin_end = true;
if ($i > 7 && !strcasecmp(substr($file, $i - 8, 9), "DELIMITER") && trim($query) == '') {
$delimiter = '';
do {
$delimiter .= $file[$i];
} while (++$i < strlen($file) && $file[$i] != PHP_EOL)
$delimiter = trim($delimiter);
}
if ($file[$i] == '\'' || $file[$i] == '"')
if ($substring_delimiter) {
if ($substring_delimiter == $file[$i] && !$last_was_backslash)
$substring_delimiter = "";
} else {
$substring_delimiter = $file[$i];
}
if ($outside_begin_end && !$substring_delimiter && !strcasecmp($delimiter, substr($file, $i))) {
$sql->query($query); // where $sql is a mysqli instance
$query = "";
} else {
$query .= $file[$i];
}
if ($file[$i] == '\\')
$last_was_backslash = !$last_was_backslash;
else
$last_was_backslash = false;
}
if (trim($query) != "")
$sql->query($query);
Upvotes: 1