Skip to content

Instantly share code, notes, and snippets.

@olsgreen
Created September 24, 2016 17:10
Show Gist options
  • Save olsgreen/f3271980130186ad1d9e47f79eb8ad76 to your computer and use it in GitHub Desktop.
Save olsgreen/f3271980130186ad1d9e47f79eb8ad76 to your computer and use it in GitHub Desktop.
mysqli version of David Walsh's PHP MySQL backup script
/* backup the db OR just a table
* See original: https://davidwalsh.name/backup-mysql-database-php
*/
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$link = mysqli_connect($host,$user,$pass,$name);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = $link->query('SHOW TABLES');
while($row = $result->fetch_row())
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
foreach($tables as $table)
{
$result = $link->query('SELECT * FROM '.$table);
$num_fields = $result->field_count;
$return.= 'DROP TABLE '.$table.';';
$row2 = $link->query('SHOW CREATE TABLE '.$table);
$row2 = $row2->fetch_array();
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = $result->fetch_array())
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j < $num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j < ($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment