I found a PHP function to flush the mySQL database someone else had written, and then flushed it and formatted it a bit. I wanted to know if I could criticize him. I launched it, tested it on the Wordpress blog, and the DB fully recovered, but wanted to get other eyes on the code.
In particular, I am looking for reviews:
- Everything that can lead to data corruption - could not be avoided, etc.
- Violation of any best practice / principles
- Security concerns
- Everything you can see as a problem
NOTE. I am NOT looking at using mysqldump, I want to fully generate this sql backup from code. I also understand that the file name may be randomly generated, but the SQL file will also be uploaded to dropbox, and I want to fine-tune it under the same name.
Thanks!
The code:
// Variables $dbHost = 'DBHOST'; $dbUser = 'DBUSER'; $dbPassword = 'DBPASSWORD'; $dbName = 'DBNAME'; $tables = '*'; $fileName = 'mydatabase.sql'; // Logic $link = @mysql_connect($dbHost, $dbUser, $dbPassword); $db = @mysql_select_db($dbName, $link); if(!$link || !$db) die("Database Error"); //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); // Loop through tables foreach($tables as $table) { $result = mysql_query('SELECT * FROM '. $table); $num_fields = mysql_num_fields($result); $return.= 'DROP TABLE IF EXISTS ' . $table . ';'; $createTable = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table)); $return .= "\n\n" . $createTable[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 the file $handle = fopen($fileName, 'w+'); fwrite($handle, $return); fclose($handle);
php mysql backup database-backups
j34smith
source share