Skip to content

Instantly share code, notes, and snippets.

@Boztown
Created April 6, 2015 03:56
Show Gist options
  • Save Boztown/10c9f77cee456510646f to your computer and use it in GitHub Desktop.
Save Boztown/10c9f77cee456510646f to your computer and use it in GitHub Desktop.
Code to back up Wordpress database
// http://www.codesynthesis.co.uk/code-snippets/code-to-backup-a-wordpress-database
<?php
global $wpdb;
// Get a list of the tables
$tables = $wpdb->get_results('SHOW TABLES');
$upload_dir = wp_upload_dir();
$file_path = $upload_dir['basedir'] . '/backups/database-' . time() . '.sql';
$file = fopen($file_path, 'w');
foreach ($tables as $table)
{
$table_name = $table->Tables_in_wordpress;
$schema = $wpdb->get_row('SHOW CREATE TABLE ' . $table_name, ARRAY_A);
fwrite($file, $schema['Create Table'] . ';' . PHP_EOL);
$rows = $wpdb->get_results('SELECT * FROM ' . $table_name, ARRAY_A);
if( $rows )
{
fwrite($file, 'INSERT INTO ' . $table_name . ' VALUES ');
$total_rows = count($rows);
$counter = 1;
foreach ($rows as $row => $fields)
{
$line = '';
foreach ($fields as $key => $value)
{
$value = addslashes($value);
$line .= '"' . $value . '",';
}
$line = '(' . rtrim($line, ',') . ')';
if ($counter != $total_rows)
{
$line .= ',' . PHP_EOL;
}
fwrite($file, $line);
$counter++;
}
fwrite($file, '; ' . PHP_EOL);
}
}
fclose($file);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment