Import mysql dump using php
Posted by Raj
Import mysql dump using php
In this article,I will explain How to import Mysql database using PHP.I have written php Script to restore a phpMyAdmin MySQL dump.I have mysql dump file(mydb.sql).
Below code will also import Triggers and Stored Procedures.Importing the mysqldump file using php script would be the easiest and fastest solution.
Note: importing a mysqldump file does not import triggers due to some permission problems.Make sure that the user importing the database has the SUPER priveledge.
import.php
define('PMA_CHK_DROP', 1);
function PMA_checkTimeout()
{
global $timestamp, $maximum_time, $timeout_passed;
if ($maximum_time == 0) {
return FALSE;
} elseif ($timeout_passed) {
return TRUE;
} elseif ((time() - $timestamp) > ($maximum_time - 5)) {
$timeout_passed = TRUE;
return TRUE;
} else {
return FALSE;
}
}
function PMA_detectCompression($filepath)
{
$file = @fopen($filepath, 'rb');
if (!$file) {
return FALSE;
}
$test = fread($file, 4);
$len = strlen($test);
fclose($file);
if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
return 'application/gzip';
}
if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
return 'application/bzip2';
}
if ($len >= 4 && $test == "PK\003\004") {
return 'application/zip';
}
return 'none';
}
function PMA_importRunQuery($sql = '', $full = '', $controluser = false)
{
global $import_run_buffer, $go_sql, $complete_query, $display_query,
$sql_query, $my_die, $error, $reload,
$skip_queries, $executed_queries, $max_sql_len, $read_multiply,
$cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
$read_multiply = 1;
if (isset($import_run_buffer)) {
if ($skip_queries > 0) {
$skip_queries--;
} else {
if (!empty($import_run_buffer['sql']) &&
trim($import_run_buffer['sql']) != '') {
$max_sql_len = max($max_sql_len,
strlen($import_run_buffer['sql']));
if (!$sql_query_disabled) {
$sql_query .= $import_run_buffer['full'];
}
if (!$cfg['AllowUserDropDatabase']
&& !$is_superuser
&& preg_match('@^[[:space:]]*DROP[[:space:]]+(IF
EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])) {
$GLOBALS['message'] =
PMA_Message::error('strNoDropDatabases');
$error = TRUE;
} else {
$executed_queries++;
if ($run_query && $GLOBALS['finished'] && empty($sql)
&& !$error && (
(!empty($import_run_buffer['sql']) &&
preg_match('/^[\s]*(SELECT|SHOW|HANDLER)/i', $import_run_buffer['sql'])) ||
($executed_queries == 1)
)) {
$go_sql = TRUE;
if (!$sql_query_disabled) {
$complete_query = $sql_query;
$display_query = $sql_query;
} else {
$complete_query = '';
$display_query = '';
}
$sql_query = $import_run_buffer['sql'];
} elseif ($run_query) {
if ($controluser) {
$result =
PMA_query_as_cu($import_run_buffer['sql']);
} else {
$result =
PMA_DBI_try_query($import_run_buffer['sql']);
}
$msg = '# ';
if ($result === FALSE) { // execution failed
if (!isset($my_die)) {
$my_die = array();
}
$my_die[] = array('sql' =>
$import_run_buffer['full'], 'error' => PMA_DBI_getError());
if ($cfg['VerboseMultiSubmit']) {
$msg .= $GLOBALS['strError'];
}
if (!$cfg['IgnoreMultiSubmitErrors']) {
$error = TRUE;
return;
}
} elseif ($cfg['VerboseMultiSubmit']) {
$a_num_rows = (int)@PMA_DBI_num_rows($result);
$a_aff_rows = (int)@PMA_DBI_affected_rows();
if ($a_num_rows > 0) {
$msg .= $GLOBALS['strRows'] . ': ' .
$a_num_rows;
} elseif ($a_aff_rows > 0) {
$msg .=
sprintf($GLOBALS['strRowsAffected'], $a_aff_rows);
} else {
$msg .= $GLOBALS['strEmptyResultSet'];
}
}
if (!$sql_query_disabled) {
$sql_query .= $msg . "\n";
}
if ($result != FALSE &&
preg_match('@^[\s]*USE[[:space:]]*([\S]+)@i', $import_run_buffer['sql'],
$match)) {
$db = trim($match[1]);
$db = trim($db,';');
$reload = TRUE;
}
if ($result != FALSE &&
preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF
EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im',
$import_run_buffer['sql'])) {
$reload = TRUE;
}
}
}
}
elseif (!empty($import_run_buffer['full'])) {
if ($go_sql) {
$complete_query .= $import_run_buffer['full'];
$display_query .= $import_run_buffer['full'];
} else {
if (!$sql_query_disabled) {
$sql_query .= $import_run_buffer['full'];
}
}
}
if (! $go_sql && $run_query) {
if ($cfg['VerboseMultiSubmit'] && ! empty($sql_query)) {
if (strlen($sql_query) > 50000 || $executed_queries >
50 || $max_sql_len > 1000) {
$sql_query = '';
$sql_query_disabled = TRUE;
}
} else {
if (strlen($sql_query) > 10000 || $executed_queries >
10 || $max_sql_len > 500) {
$sql_query = '';
$sql_query_disabled = TRUE;
}
}
}
}
}
if (!empty($sql) || !empty($full)) {
$import_run_buffer = array('sql' => $sql, 'full' => $full);
} else {
unset($GLOBALS['import_run_buffer']);
}
}
function PMA_importGetNextChunk($size = 32768)
{
global $compression, $import_handle, $charset_conversion,
$charset_of_file,
$charset, $read_multiply;
$compression="none";
if ($read_multiply <= 8) {
$size *= $read_multiply;
} else {
$size *= 8;
}
$read_multiply++;
if ($size > $GLOBALS['read_limit']) {
$size = $GLOBALS['read_limit'];
}
if (PMA_checkTimeout()) {
return FALSE;
}
if ($GLOBALS['finished']) {
return TRUE;
}
if ($GLOBALS['import_file'] == 'none') {
if (strlen($GLOBALS['import_text']) < $size) {
$GLOBALS['finished'] = TRUE;
return $GLOBALS['import_text'];
} else {
$r = substr($GLOBALS['import_text'], 0, $size);
$GLOBALS['offset'] += $size;
$GLOBALS['import_text'] = substr($GLOBALS['import_text'],
$size);
return $r;
}
}
switch ($compression) {
case 'application/bzip2':
$result = bzread($import_handle, $size);
$GLOBALS['finished'] = feof($import_handle);
break;
case 'application/gzip':
$result = gzread($import_handle, $size);
$GLOBALS['finished'] = feof($import_handle);
break;
case 'application/zip':
$result = substr($GLOBALS['import_text'], 0, $size);
$GLOBALS['import_text'] = substr($GLOBALS['import_text'],
$size);
$GLOBALS['finished'] = empty($GLOBALS['import_text']);
break;
case 'none':
$result = fread($import_handle, $size);
$GLOBALS['finished'] = feof($import_handle);
break;
}
$GLOBALS['offset'] += $size;
if ($charset_conversion) {
return PMA_convert_string($charset_of_file, $charset, $result);
} else {
if ($GLOBALS['offset'] == $size) {
// UTF-8
if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
$result = substr($result, 3);
// UTF-16 BE, LE
} elseif (strncmp($result, "\xFE\xFF", 2) == 0 ||
strncmp($result, "\xFF\xFE", 2) == 0) {
$result = substr($result, 2);
}
}
return $result;
}
}
?>
In this article,I will explain How to import Mysql database using PHP.I have written php Script to restore a phpMyAdmin MySQL dump.I have mysql dump file(mydb.sql).
Below code will also import Triggers and Stored Procedures.Importing the mysqldump file using php script would be the easiest and fastest solution.
Note: importing a mysqldump file does not import triggers due to some permission problems.Make sure that the user importing the database has the SUPER priveledge.
import.php
define('PMA_CHK_DROP', 1);
function PMA_checkTimeout()
{
global $timestamp, $maximum_time, $timeout_passed;
if ($maximum_time == 0) {
return FALSE;
} elseif ($timeout_passed) {
return TRUE;
} elseif ((time() - $timestamp) > ($maximum_time - 5)) {
$timeout_passed = TRUE;
return TRUE;
} else {
return FALSE;
}
}
function PMA_detectCompression($filepath)
{
$file = @fopen($filepath, 'rb');
if (!$file) {
return FALSE;
}
$test = fread($file, 4);
$len = strlen($test);
fclose($file);
if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
return 'application/gzip';
}
if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
return 'application/bzip2';
}
if ($len >= 4 && $test == "PK\003\004") {
return 'application/zip';
}
return 'none';
}
function PMA_importRunQuery($sql = '', $full = '', $controluser = false)
{
global $import_run_buffer, $go_sql, $complete_query, $display_query,
$sql_query, $my_die, $error, $reload,
$skip_queries, $executed_queries, $max_sql_len, $read_multiply,
$cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
$read_multiply = 1;
if (isset($import_run_buffer)) {
if ($skip_queries > 0) {
$skip_queries--;
} else {
if (!empty($import_run_buffer['sql']) &&
trim($import_run_buffer['sql']) != '') {
$max_sql_len = max($max_sql_len,
strlen($import_run_buffer['sql']));
if (!$sql_query_disabled) {
$sql_query .= $import_run_buffer['full'];
}
if (!$cfg['AllowUserDropDatabase']
&& !$is_superuser
&& preg_match('@^[[:space:]]*DROP[[:space:]]+(IF
EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])) {
$GLOBALS['message'] =
PMA_Message::error('strNoDropDatabases');
$error = TRUE;
} else {
$executed_queries++;
if ($run_query && $GLOBALS['finished'] && empty($sql)
&& !$error && (
(!empty($import_run_buffer['sql']) &&
preg_match('/^[\s]*(SELECT|SHOW|HANDLER)/i', $import_run_buffer['sql'])) ||
($executed_queries == 1)
)) {
$go_sql = TRUE;
if (!$sql_query_disabled) {
$complete_query = $sql_query;
$display_query = $sql_query;
} else {
$complete_query = '';
$display_query = '';
}
$sql_query = $import_run_buffer['sql'];
} elseif ($run_query) {
if ($controluser) {
$result =
PMA_query_as_cu($import_run_buffer['sql']);
} else {
$result =
PMA_DBI_try_query($import_run_buffer['sql']);
}
$msg = '# ';
if ($result === FALSE) { // execution failed
if (!isset($my_die)) {
$my_die = array();
}
$my_die[] = array('sql' =>
$import_run_buffer['full'], 'error' => PMA_DBI_getError());
if ($cfg['VerboseMultiSubmit']) {
$msg .= $GLOBALS['strError'];
}
if (!$cfg['IgnoreMultiSubmitErrors']) {
$error = TRUE;
return;
}
} elseif ($cfg['VerboseMultiSubmit']) {
$a_num_rows = (int)@PMA_DBI_num_rows($result);
$a_aff_rows = (int)@PMA_DBI_affected_rows();
if ($a_num_rows > 0) {
$msg .= $GLOBALS['strRows'] . ': ' .
$a_num_rows;
} elseif ($a_aff_rows > 0) {
$msg .=
sprintf($GLOBALS['strRowsAffected'], $a_aff_rows);
} else {
$msg .= $GLOBALS['strEmptyResultSet'];
}
}
if (!$sql_query_disabled) {
$sql_query .= $msg . "\n";
}
if ($result != FALSE &&
preg_match('@^[\s]*USE[[:space:]]*([\S]+)@i', $import_run_buffer['sql'],
$match)) {
$db = trim($match[1]);
$db = trim($db,';');
$reload = TRUE;
}
if ($result != FALSE &&
preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF
EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im',
$import_run_buffer['sql'])) {
$reload = TRUE;
}
}
}
}
elseif (!empty($import_run_buffer['full'])) {
if ($go_sql) {
$complete_query .= $import_run_buffer['full'];
$display_query .= $import_run_buffer['full'];
} else {
if (!$sql_query_disabled) {
$sql_query .= $import_run_buffer['full'];
}
}
}
if (! $go_sql && $run_query) {
if ($cfg['VerboseMultiSubmit'] && ! empty($sql_query)) {
if (strlen($sql_query) > 50000 || $executed_queries >
50 || $max_sql_len > 1000) {
$sql_query = '';
$sql_query_disabled = TRUE;
}
} else {
if (strlen($sql_query) > 10000 || $executed_queries >
10 || $max_sql_len > 500) {
$sql_query = '';
$sql_query_disabled = TRUE;
}
}
}
}
}
if (!empty($sql) || !empty($full)) {
$import_run_buffer = array('sql' => $sql, 'full' => $full);
} else {
unset($GLOBALS['import_run_buffer']);
}
}
function PMA_importGetNextChunk($size = 32768)
{
global $compression, $import_handle, $charset_conversion,
$charset_of_file,
$charset, $read_multiply;
$compression="none";
if ($read_multiply <= 8) {
$size *= $read_multiply;
} else {
$size *= 8;
}
$read_multiply++;
if ($size > $GLOBALS['read_limit']) {
$size = $GLOBALS['read_limit'];
}
if (PMA_checkTimeout()) {
return FALSE;
}
if ($GLOBALS['finished']) {
return TRUE;
}
if ($GLOBALS['import_file'] == 'none') {
if (strlen($GLOBALS['import_text']) < $size) {
$GLOBALS['finished'] = TRUE;
return $GLOBALS['import_text'];
} else {
$r = substr($GLOBALS['import_text'], 0, $size);
$GLOBALS['offset'] += $size;
$GLOBALS['import_text'] = substr($GLOBALS['import_text'],
$size);
return $r;
}
}
switch ($compression) {
case 'application/bzip2':
$result = bzread($import_handle, $size);
$GLOBALS['finished'] = feof($import_handle);
break;
case 'application/gzip':
$result = gzread($import_handle, $size);
$GLOBALS['finished'] = feof($import_handle);
break;
case 'application/zip':
$result = substr($GLOBALS['import_text'], 0, $size);
$GLOBALS['import_text'] = substr($GLOBALS['import_text'],
$size);
$GLOBALS['finished'] = empty($GLOBALS['import_text']);
break;
case 'none':
$result = fread($import_handle, $size);
$GLOBALS['finished'] = feof($import_handle);
break;
}
$GLOBALS['offset'] += $size;
if ($charset_conversion) {
return PMA_convert_string($charset_of_file, $charset, $result);
} else {
if ($GLOBALS['offset'] == $size) {
// UTF-8
if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
$result = substr($result, 3);
// UTF-16 BE, LE
} elseif (strncmp($result, "\xFE\xFF", 2) == 0 ||
strncmp($result, "\xFF\xFE", 2) == 0) {
$result = substr($result, 2);
}
}
return $result;
}
}
?>
Example :How to import mysql dump (.sql) into a database using PHP Script?
import_mysql.php
ini_set("display_errors","1");
$user_name = "root";
$password = "";
$database = "mydb";
$server = "localhost";
$conn = mysql_connect($server, $user_name, $password);
mysql_select_db($database);
include("import.php");
$timeout_passed = FALSE;
$error = FALSE;
$read_multiply = 1;
$finished = FALSE;
$offset = 0;
$max_sql_len = 0;
$file_to_unlink = '';
$sql_query = '';
$sql_query_disabled = FALSE;
$go_sql = FALSE;
$executed_queries = 0;
$run_query = TRUE;
$charset_conversion = FALSE;
$reset_charset = FALSE;
$bookmark_created = FALSE;
$import_file='mydb.sql';
$import_handle = @fopen($import_file, 'r');
$memory_limit = trim(@ini_get('memory_limit'));
if (empty($memory_limit)) {
$memory_limit = 2 * 1024 * 1024;
}
if ($memory_limit == -1) {
$memory_limit = 10 * 1024 * 1024;
}
if (strtolower(substr($memory_limit, -1)) == 'm') {
$memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024;
} elseif (strtolower(substr($memory_limit, -1)) == 'k') {
$memory_limit = (int)substr($memory_limit, 0, -1) * 1024;
} elseif (strtolower(substr($memory_limit, -1)) == 'g') {
$memory_limit = (int)substr($memory_limit, 0, -1) * 1024 * 1024 * 1024;
} else {
$memory_limit = (int)$memory_limit;
}
$read_limit = $memory_limit / 8;
$buffer = '';
$sql = '';
$start_pos = 0;
$i = 0;
$len= 0;
$big_value = 2147483647;
$sql_delimiter = ';';
$GLOBALS['finished'] = false;
while (!($GLOBALS['finished'] && $i >= $len) && !$error &&
!$timeout_passed) {
$data = PMA_importGetNextChunk();
if ($data === FALSE) {
$offset -= strlen($buffer);
break;
} elseif ($data === TRUE) {
} else {
$buffer .= $data;
unset($data);
if ((strpos($buffer, $sql_delimiter, $i) === FALSE) &&
!$GLOBALS['finished']) {
continue;
}
}
$len = strlen($buffer);
while ($i < $len) {
$found_delimiter = false;
$old_i = $i;
if (preg_match('/(\'|"|#|-- |\/\*|`|(?i)DELIMITER)/', $buffer,
$matches, PREG_OFFSET_CAPTURE, $i)) {
$first_position = $matches[1][1];
} else {
$first_position = $big_value;
}
$first_sql_delimiter = strpos($buffer, $sql_delimiter, $i);
if ($first_sql_delimiter === FALSE) {
$first_sql_delimiter = $big_value;
} else {
$found_delimiter = true;
}
$i = min($first_position, $first_sql_delimiter);
if ($i == $big_value) {
$i = $old_i;
if (!$GLOBALS['finished']) {
break;
}
if (trim($buffer) == '') {
$buffer = '';
$len = 0;
break;
}
$i = strlen($buffer) - 1;
}
$ch = $buffer[$i];
if (strpos('\'"`', $ch) !== FALSE) {
$quote = $ch;
$endq = FALSE;
while (!$endq) {
$pos = strpos($buffer, $quote, $i + 1);
if ($pos === FALSE) {
if ($GLOBALS['finished']) {
$endq = TRUE;
$i = $len - 1;
}
$found_delimiter = false;
break;
}
$j = $pos - 1;
while ($buffer[$j] == '\\') $j--;
$endq = (((($pos - 1) - $j) % 2) == 0);
$i = $pos;
if ($first_sql_delimiter < $pos) {
$found_delimiter = false;
}
}
if (!$endq) {
break;
}
$i++;
if ($GLOBALS['finished'] && $i == $len) {
$i--;
} else {
continue;
}
}
if ((($i == ($len - 1) && ($ch == '-' || $ch == '/'))
|| ($i == ($len - 2) && (($ch == '-' && $buffer[$i + 1] == '-')
|| ($ch == '/' && $buffer[$i + 1] == '*')))) &&
!$GLOBALS['finished']) {
break;
}
if ($ch == '#'
|| ($i < ($len - 1) && $ch == '-' && $buffer[$i + 1] == '-'
&& (($i < ($len - 2) && $buffer[$i + 2] <= ' ')
|| ($i == ($len - 1) && $GLOBALS['finished'])))
|| ($i < ($len - 1) && $ch == '/' && $buffer[$i + 1] == '*')
) {
if ($start_pos != $i) {
$sql .= substr($buffer, $start_pos, $i - $start_pos);
}
$j = $i;
$i = strpos($buffer, $ch == '/' ? '*/' : "\n", $i);
if ($i === FALSE) {
if ($GLOBALS['finished']) {
$i = $len - 1;
} else {
break;
}
}
if ($ch == '/') {
if ($buffer[$j + 2] == '!') {
$comment = substr($buffer, $j + 3, $i - $j - 3);
}
$i++;
}
$i++;
$start_pos = $i;
if ($i == $len) {
$i--;
} else {
continue;
}
}
if (strtoupper(substr($buffer, $i, 9)) == "DELIMITER"
&& ($buffer[$i + 9] <= ' ')
&& ($i < $len - 11)
&& strpos($buffer, "\n", $i + 11) !== FALSE) {
$new_line_pos = strpos($buffer, "\n", $i + 10);
$sql_delimiter = substr($buffer, $i + 10, $new_line_pos - $i -
10);
$i = $new_line_pos + 1;
$start_pos = $i;
continue;
}
if ($found_delimiter || ($GLOBALS['finished'] && ($i == $len - 1)))
{
$tmp_sql = $sql;
if ($start_pos < $len) {
$length_to_grab = $i - $start_pos;
if (! $found_delimiter) {
$length_to_grab++;
}
$tmp_sql .= substr($buffer, $start_pos, $length_to_grab);
unset($length_to_grab);
}
$error=0;
if (! preg_match('/^([\s]*;)*$/', trim($tmp_sql))) {
$sql = $tmp_sql;
if (!$result = mysql_query($sql))
{
$dbErr = true;
}
$buffer = substr($buffer, $i + strlen($sql_delimiter));
$len = strlen($buffer);
$sql = '';
$i = 0;
$start_pos = 0;
if ((strpos($buffer, $sql_delimiter) === FALSE) &&
!$GLOBALS['finished']) {
break;
}
} else {
$i++;
$start_pos = $i;
}
}
}
}
?>
I hope this will help you to import mysqldump file using php script.
Note: importing a mysqldump file does not import triggers due to some permission problems.Make sure that the user importing the database has the SUPER priveledge.
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
mysqldump import script,
mysqldump php script,
php database import,
php import database,
php mysqldump,
php mysqldump import,
php mysqldump script,
restore ysqldump
.You can leave a response, or trackback from your own site.