他の誰かが書いた mySQL データベースをダンプする PHP 関数を見つけ、クリーンアップして少しフォーマットしました。私はそれについて批評を得ることができるかどうか知りたかった. 私はそれを実行し、Wordpress ブログでテストし、DB は完全に復元されましたが、コードに別の目を向けたいと思っていました。
具体的には、次の点についてフィードバックを求めています。
- データを破損する可能性のあるもの - 適切にエスケープしないなど
- ベストプラクティス/原則への違反
- セキュリティ上の問題
- その他、問題と思われるもの
注: mysqldump を使用するつもりはありません。この SQL バックアップをコードから完全に生成したいと考えています。また、ファイル名がランダムに生成される可能性があることも認識していますが、SQL ファイルもドロップボックスにアップロードされるため、同じ名前でバージョンを作成したいと考えています。
ありがとう!
コード:
// 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);