July 24, 2008 by Alex Polski

Backing up MySQL tables under extremal conditions

I guess every web developer has ever had a situation when he needed to get the dump of MySQL table but standard tools like phpMyAdmin or mysqldump were unavailable, but you had an ability to run PHP script. Some days ago I had similar situation and now I want to share this solution with you.

First of all, let’s get the table structure. It’s more simpler.

$sql = "show create table test_table";
$res = mysql_query($sql);
$data = mysql_fetch_assoc($res);
echo $data['Create Table'];

This PHP script prints SQL string for ‘test_table’ table creation.

And now let’s get the table data.

$sql = "select * from test_table";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
  $fields = array();
  $values = array();
  foreach ($row as $key => $value) {
    array_push($fields, addslashes($key));
    array_push($values, '\'' . addslashes($value) . '\'');
  }
  $fields = implode(', ', $fields);
  $values = implode(', ', $values);
  echo "insert into test_table ($fields) values ($values);\n";
}

Note, if the table contains a lot of data, you will need to call set_time_limit(0) function.

The books I recommend:

Share and Enjoy:
  • del.icio.us
  • Digg
  • Reddit
  • Ma.gnolia
  • Technorati
  • Propeller
  • Facebook
  • StumbleUpon
  • Furl
  • blogmarks
  • Google
  • YahooMyWeb
  • E-mail this story to a friend!
This entry was posted on Thursday, July 24, 2008 at 8:08 am and is filed under MySQL. You can leave a response, or trackback from your own site.

Related posts

« Add Perl and PHP search engine plugins to your browser

How to develop a good scraper on Perl - Lesson 1 »



Leave a Reply