I am using the Database Backup script by David Walsh(http://davidwalsh.name/backup-mysql-database-php) to backup my MYSQL database as a .sql file to my server.
I created a user named backup and gave it all privileges(just to make sure). Then I put the code into a php file and setup a cron job to run the php file.
This is the code:
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$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 '.$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('../backup/db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
backup_tables('localhost','alupto_backup','pass','*');
When the cron job runs, the backup does not work and I receive an email with the error that appears:
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home5/ideapale/public_html/amatorders_basic/admin/backup.php on line 18
On line 18 is this code:
while($row = mysql_fetch_row($result))
When I run the SQL(SHOW TABLES) in phpMyAdmin, it works fine and shows me a list of all the tables. But for some reason, I am receiving an error when the php file tries to run the SQL.
Why is my database backup script not working?