Skip to content

Easily Restore your MySQL Database from PHP

by jginn on February 25, 2010

This week I found myself needing to restore a MySQL database on a Windows server, the host of which left me no access to MySQL other than the ability to create a database and users. If you find yourself in the same boat, here is a PHP script I used to perform my restore:


<?php

$myFile = 'backupFileName.sql';
$myHost = 'hostName--usually localhost';
$username = 'username';
$myPass = 'password';
$myDB = 'nameOfDb';

mysql_connect($myHost, $username, $myPass) or die('Back to the drawing board: ' . mysql_error());
mysql_select_db($myDB) or die('Back to the drawing board: ' . mysql_error());

$sqlEntry = '';
$rawFileData = file($myFile);

foreach ($rawFileData as $entry)
{
// strip out comments
if (substr($entry, 0, 2) == '--' || $entry == '')
continue;

// add line to the sql statement
$sqlEntry .= $entry;

// if line ends with semicolon then you know it completes the sql statement
// go ahead and execute the query and reset the sql variable
if (substr(trim($entry), -1, 1) == ';')
{
mysql_query($sqlEntry) or print('Query did not execute properly: '' . $sqlEntry . '': ' . mysql_error());
$sqlEntry = '';
}
}

?>

Just change the values for the variables $myHost, $myFile, $username, $myPass, and $myDB and your set. If your backup file is not in the same folder as this script make sure you include at least the relative path in the value.
Hope this helps!


Leave a Comment

Leave a Reply

Note: XHTML is allowed.

Subscribe to this comment feed via RSS