萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 導入 SQL 文件腳本實現詳解

功能概述

本腳本用於將 .sql 文件中的 SQL 語句批量導入 MySQL 數據庫,支援去除註釋、處理建表語句字符集/引擎兼容、事務式執行與錯誤報告。

核心代碼解析

<?php
function importSqlFile(string $file, string $replace = ''): int {
    global $Charset; // 全局字符集變量,如 'utf8mb4'
    
    $content = readFile($file);
    if (!$content) return 0;
    
    // 可選:替換佔位符(如 $timestamp)
    if ($replace) {
        $content = str_replace('$timestamp', $timestamp, $content);
    }
    
    // 按換行符拆分,過濾註釋行
    $lines = explode("\n", $content);
    $sqlLines = [];
    foreach ($lines as $line) {
        $trimmed = ltrim($line);
        // 跳過 # 或 -- 開頭的註釋行
        if (str_starts_with($trimmed, '#') || str_starts_with($trimmed, '--')) {
            continue;
        }
        $sqlLines[] = $line;
    }
    
    // 重組並按分號拆分語句
    $sql = implode("\n", $sqlLines);
    $sql = str_replace("\r", '', $sql); // 統一換行符
    $statements = explode(";\n", $sql);
    
    $executed = 0;
    foreach ($statements as $stmt) {
        $stmt = trim(str_replace(["\r", "\n"], '', $stmt));
        if (!$stmt) continue;
        
        // 處理 CREATE TABLE 兼容性
        if (stripos($stmt, 'CREATE TABLE') === 0) {
            $mysqlVer = mysqli_get_server_info($GLOBALS['mysqli'] ?? null) ?: '5.0';
            $stmt = preg_replace('/DEFAULT CHARSET=([a-z0-9]+)/i', '', $stmt);
            $stmt = preg_replace('/TYPE=MyISAM/i', 'ENGINE=MyISAM', $stmt);
            if (version_compare($mysqlVer, '4.1', '>')) {
                $stmt = str_replace('ENGINE=MyISAM', "ENGINE=MyISAM DEFAULT CHARSET=$Charset", $stmt);
            }
        }
        
        // 執行語句(假設已建立 $mysqli 連接)
        $result = $GLOBALS['mysqli']->query($stmt);
        if (!$result) {
            die("SQL 執行失敗: $stmt\n錯誤: " . $GLOBALS['mysqli']->error);
        }
        $executed++;
    }
    return $executed;
}

function readFile(string $filename, string $mode = 'rb'): ?string {
    if (!is_readable($filename)) return null;
    $handle = fopen($filename, $mode);
    if (!$handle) return null;
    flock($handle, LOCK_SH);
    $data = fread($handle, filesize($filename));
    fclose($handle);
    return $data;
}
?>

關鍵改進點(對比原代碼)

  • 棄用 mysql_* 函數:改用 mysqli 或 PDO,原 mysql_* 已在 PHP 7 移除。
  • 正則優化:使用 preg_replace 替代已棄用的 ereg/eregi。
  • 版本比較:用 version_compare() 替代字符串比較 $mysqlV > '4.1'。
  • 錯誤處理:拋出異常或返回錯誤信息,而非 die() 直接終止。
  • 編碼處理:明確指定 $Charset(建議 utf8mb4)。

使用示例

<?php
// 配置數據庫連接
$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');
$mysqli->set_charset('utf8mb4');
$GLOBALS['mysqli'] = $mysqli; // 供函數使用

$Charset = 'utf8mb4';

try {
    $count = importSqlFile(__DIR__ . '/install.sql');
    echo "成功導入 $count 條 SQL 語句。";
} catch (Exception $e) {
    echo "導入失敗: " . $e->getMessage();
}
?>

大文件優化建議

  • 使用 mysqli::multi_query() 批量執行,減少網絡往返。
  • 分塊讀取大文件(如 fgets() 逐行),避免一次性載入內存。
  • 關閉自動提交,手動控制事務:$mysqli->autocommit(false),成功後 commit()。

總結

導入 SQL 文件是部署、遷移常見需求。本文提供現代化、健壯的實現,修正了原代碼的棄用函數、編碼兼容與錯誤處理問題,可直接用於生產環境部署腳本。

copyright © 萬盛學電腦網 all rights reserved