1

I'm using the script I posted below and it appeared to have worked based on the email and the fact it actually generated the file. However, It didn't backup anything.

Here is the output stored in the file it created:

SET FOREIGN_KEY_CHECKS=0;

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

SET AUTOCOMMIT=0;

START TRANSACTION;

SET FOREIGN_KEY_CHECKS=1;

COMMIT;

Here is the php script being used to generate the backup:

    #!/usr/bin/php
<?php

backup_tables();

// backup all tables in db
function backup_tables()
{
    $day_of_backup = ''; //possible values: `Monday` `Tuesday` `Wednesday` `Thursday` `Friday` `Saturday` `Sunday`
    $backup_path = '/home/user/public_html/path/to/BACKUP.file/destination/'; //make sure it ends with "/"
    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = 'replace_w_ur_password';
    $db_name = 'replace_w_ur_db_name';

    //set the correct date for filename
    if (date('l') == $day_of_backup) {
        $date = date("Y-m-d");
    } else {
        //set $date to the date when last backup had to occur
        $datetime1 = date_create($day_of_backup);
        $date = date("Y-m-d", strtotime($day_of_backup.'-1 days'));
    }

    if (!file_exists($backup_path.$date.'-backup'.'.sql')) {

        //connect to db
        $link = mysqli_connect($db_host,$db_user,$db_pass);
        mysqli_set_charset($link,'utf8');
        mysqli_select_db($link,$db_name);

        //get all of the tables
        $tables = array();
        $result = mysqli_query($link, 'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }

        //disable foreign keys (to avoid errors)
        $return = 'SET FOREIGN_KEY_CHECKS=0;' . "\r\n";
        $return.= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . "\r\n";
        $return.= 'SET AUTOCOMMIT=0;' . "\r\n";
        $return.= 'START TRANSACTION;' . "\r\n";

        //cycle through
        foreach($tables as $table)
        {
            $result = mysqli_query($link, 'SELECT * FROM '.$table);
            $num_fields = mysqli_num_fields($result);
            $num_rows = mysqli_num_rows($result);
            $i_row = 0;

            //$return.= 'DROP TABLE '.$table.';'; 
            $row2 = mysqli_fetch_row(mysqli_query($link,'SHOW CREATE TABLE '.$table));
            $return.= "\n\n".$row2[1].";\n\n"; 

            if ($num_rows !== 0) {
                $row3 = mysqli_fetch_fields($result);
                $return.= 'INSERT INTO '.$table.'( ';
                foreach ($row3 as $th) 
                { 
                    $return.= '`'.$th->name.'`, '; 
                }
                $return = substr($return, 0, -2);
                $return.= ' ) VALUES';

                for ($i = 0; $i < $num_fields; $i++) 
                {
                    while($row = mysqli_fetch_row($result))
                    {
                        $return.="\n(";
                        for($j=0; $j<$num_fields; $j++) 
                        {
                            $row[$j] = addslashes($row[$j]);
                            $row[$j] = preg_replace("#\n#","\\n",$row[$j]);
                            if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                            if ($j<($num_fields-1)) { $return.= ','; }
                        }
                        if (++$i_row == $num_rows) {
                            $return.= ");"; // last row
                        } else {
                            $return.= "),"; // not last row
                        }   
                    }
                }
            }
            $return.="\n\n\n";
        }

        // enable foreign keys
        $return .= 'SET FOREIGN_KEY_CHECKS=1;' . "\r\n";
        $return.= 'COMMIT;';

        //set file path
        if (!is_dir($backup_path)) {
            mkdir($backup_path, 0755, true);
        }

        //delete old file
        //$old_date = date("Y-m-d", strtotime('-4 weeks', strtotime($date)));
        //$old_file = $backup_path.$old_date.'-backup'.'.sql';
        //if (file_exists($old_file)) unlink($old_file);

        //save file
        $handle = fopen($backup_path.$date.'-backup'.'.sql','w+');
        fwrite($handle,$return);
        fclose($handle);
    }
}

?>

Any recommendations or leads on why it wouldn't actually backup all the tables would be greatly appreciated.

D.Davis
  • 15
  • 1
  • 10
  • Seeing `addslashes` in here is super not encouraging, that's notoriously flawed. Is there any reason you're not using [`mysqldump`](https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html) which can do all this and more? – tadman May 16 '17 at 18:07
  • I know that I can go to myphpadmin and export manually to back up to a single downloadable file, but I wanted this action to reoccur based on a cron schedule. This was a recommendation I found with a few edits. 1st I mainly wanted to catch the content table, but when that didn't work I took out the name of the content table so it would backup the entire database. Then of course I had to enter my own credentials. I also left $day_of_backup as ' ' instead of designating a day because I plan on doing this nightly at midnight with a cron job. – D.Davis May 16 '17 at 18:39
  • What edits would you recommend, in detail please? – D.Davis May 16 '17 at 18:39
  • This developer is also sharing the same php script piece which also includes the addslashes - https://davidwalsh.name/backup-mysql-database-php. I don't think I got it from this site, but the script is very much the same. He/she must have been sharing on another forum, possibly this one since i mainly use this one and w3schools. – D.Davis May 16 '17 at 18:42
  • That code uses `mysql_query` so it's obsolete and shouldn't be trusted for anything. That entire subsystem was thrown out in PHP 7 because it was so awful. That script is also pointless: `mysqldump` does the job properly, consistently, and is supported by the MySQL team directly. – tadman May 16 '17 at 18:44
  • Ok, so i need to figure out how I'm going to do this in mysqldump? Thanks for the guidance tadman. – D.Davis May 16 '17 at 18:48
  • Do you think this would work? $backupFile"; system($command); include 'closedb.php'; ?> GOT IT FROM: http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/using-php-to-backup-mysql-databases.aspx – D.Davis May 16 '17 at 18:53
  • At that point you may as well use a shell script in your cron job. There's no reason to bridge through PHP. – tadman May 16 '17 at 19:08
  • My plan was to develop this to cover several processes. This script will eventually backup the db to a designated location, name it based on the date of the backup, zip it, then email the zip to me. First things first, getting the backup to take. This is what I have so far: #!/usr/bin/php $backupFile"; system($command); include 'closedb.php'; ?> – D.Davis May 16 '17 at 19:17
  • Just write a shell script. PHP will only get in the way here. – tadman May 16 '17 at 19:26
  • Can all that i mentioned above be done with a shell script? I don't know anything about shell script. Let along writing it from scratch. – D.Davis May 16 '17 at 19:39
  • You're already doing a shell script when you call `system`, it's just a tiny one-liner. Expand on that a little to run multiple times if you need to. – tadman May 16 '17 at 19:58
  • for what ever reason it seems to not be taking my pw. I have my pw, one I know to be correct because it lets me in via ftp and via WHM. This is the error i'm getting " adding: -Enter password: mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO) when trying to connect (stored 0%) Content-type: text/html; charset=UTF-8 " – D.Davis May 16 '17 at 20:06
  • where and what do I enter to call system? – D.Davis May 16 '17 at 20:07
  • Figure out what `system` called in your PHP code, exactly, and do that in a shell script. You should get identical results. You can also create a personal `my.cnf` file that [includes the password options](http://stackoverflow.com/questions/9293042/how-to-perform-a-mysqldump-without-a-password-prompt) to avoid having to set so many command-line arguments. – tadman May 17 '17 at 01:11

0 Answers0