Sql dump file running in php

When you do projects, sometime it needs to keep option at the admin backend to keep backup of db and restoring option. For this you need to export the sql of the db in a sql file which is not much problem in php. But the problem is if you want to execute the saved sql file as php has some limitation of reading the sql.

Other case, suppose you get a huge sql file that need to dump (more than 1Mb), and you only have access to phpmyadmin and php. It is not actually possible most of the time to get it processed by phpmyadmin.

Here I will show how to import the sql file in php.

First need to set the limit of php to 0. Then, the need to parses the sql and create an array of sql statements from semicolon separated instructions. Rest of the things are easy …. let us have a look


set_time_limit(0); // For running the script with no time limit
$sql_statements = file_get_contents ("your file.sql);
$arr_sql = preg_split('/;[\n\r]+/',$sql_statements); // Parsing the file content by preg_split
reset($arr_sql);
$error = '';
while (list($key,$value)=each($arr_sql)) {
if (trim($value)!="") {
if (!mysql_query($value)){
echo mysql_error();
}
}
}

Happy Codding!!!! Cheers!

Advertisements
  1. #1 by krishna on November 1, 2012 - 2:27 PM

    Thanks for your code…This code is working fine. but its not executing procedure queries. How can i handle procedures ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: