The error
Fatal error: Call to undefined function backup_tables()
The code:
<?php
$doBackupDB=$_REQUEST["doBackupDB"];
if($doBackupDB=='yes')
{
// create new fresh backup
// dont forget to give it hotname, username, password and db requirements in line below
backup_tables($hostname,$username,$password,$dbname);
/* backup the db OR just a table */
// call db variables from your db
function backup_tables($hostname,$username,$password,$dbname,$tables = '*')
{
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($dbname,$link);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$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('backups/db-backup-'.time().'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
}
?>
The Confusion/Problem
Now I know it's happening because of this if statement:
$doBackupDB=$_REQUEST["doBackupDB"];
if($doBackupDB=='yes')
{
// backup code
}
Basically I want to trigger this backup by clicking a button, like this:
backup.php?doBackupDB=yes
If I don't use this if statement, backup is being created on page load, because the script executes automatically.
If i try to control it and use an if statement to check that if button was clicked and the page reloads and the variable was passed to dobackup
then script should run --- here the error occurs.
Please advise. For now, I have to empty the backup directory before backup script runs, on page load, to get the fresh backup by this script and to delete old.
mysql_query
functions is dangerous enough. Using them to make backups is outrageous. – tadman Jan 31 at 4:49mysqli
is a decent alternative if you can't use PDO for whatever reason.mysql_query
is being phased out and will be removed entirely in future versions of PHP. – tadman Jan 31 at 7:06