Hongmu Notes
Home Language Notes PHP obtains the remote .sql.zip file, then clears the data, and then imports the .sql.zip into the mysql database
Language Notes PHP PHP and mysql

PHP obtains the remote .sql.zip file, then clears the data, and then imports the .sql.zip into the mysql database

PHP obtains the remote .sql.zip file, then clears the data, and then imports the .sql.zip into the mysql database

You can use PHP's mysqli extension to operate the MySQL database. The following is a sample code to obtain the remote .sql.zip file, then clear the database, and then import the .sql.zip into the mysql database:

<?php
// 设置MySQL数据库连接信息
$host = 'localhost';
$dbname = 'my_database';
$user = 'my_username';
$password = 'my_password';

// 连接MySQL数据库
$mysqli = new mysqli($host, $user, $password, $dbname);

// 检查连接是否成功
if ($mysqli->connect_errno) {
    die('连接MySQL数据库失败:' . $mysqli->connect_error);
}

// 获取远程的.sql.zip文件并保存到本地
$remoteFileUrl = 'http://example.com/remote_sql.zip';
$localZipFilePath = tempnam(sys_get_temp_dir(), 'download_');
copy($remoteFileUrl, $localZipFilePath);

// 解压缩.sql文件
$zip = new ZipArchive;
$res = $zip->open($localZipFilePath);
if ($res === TRUE) {
    $zip->extractTo(sys_get_temp_dir());
    $zip->close();

    // 获取.sql文件名
    $sqlFilename = '';
    $sqlFiles = scandir(sys_get_temp_dir());
    foreach ($sqlFiles as $filename) {
        if (pathinfo($filename, PATHINFO_EXTENSION) == 'sql') {
            $sqlFilename = $filename;
            break;
        }
    }

    // 清空数据库
    $tables = array();
    $result = $mysqli->query('SHOW TABLES');
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        $tables[] = $row[0];
    }
    $result->close();
    foreach ($tables as $table) {
        $mysqli->query("DROP TABLE IF EXISTS $table");
    }

    // 导入.sql文件
    $sqlFile = file_get_contents(sys_get_temp_dir() . '/' . $sqlFilename);
    $mysqli->multi_query($sqlFile);

    // 删除临时文件
    unlink($localZipFilePath);
    unlink(sys_get_temp_dir() . '/' . $sqlFilename);
} else {
    die('解压缩文件失败');
}

// 关闭MySQL连接
$mysqli->close();
?>

The above code first connects to the MySQL database, and then uses the copy function to obtain the remote .zip file and save it to the local temporary directory.

Then use the ZipArchive class to decompress the .zip file, obtain the .sql file name, and clear the database.

Finally, use the multi_query function in the mysqli extension to import the .sql file into the MySQL database, and finally delete the temporary file.

Encapsulate into a function

 隐藏内容:会员可查看
/**
 * 下载远程的 SQL ZIP 文件,清空数据库,导入 SQL 数据
 * @param string $remoteUrl 远程 SQL ZIP 文件地址
 * @param string $dbHost 数据库主机地址
 * @param string $dbName 数据库名称
 * @param string $dbUser 数据库用户名
 * @param string $dbPassword 数据库密码
 * @throws Exception 下载、解压或导入 SQL 文件失败时抛出异常
 */
function importSqlZip($remoteUrl, $dbHost, $dbName, $dbUser, $dbPassword)
{
    // 下载远程 SQL ZIP 文件并保存到本地
    $tempZip = tempnam(sys_get_temp_dir(), 'download_');
    $fp = fopen($tempZip, 'w');
    $ch = curl_init($remoteUrl);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    $success = curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    if (!$success) {
        throw new Exception('Failed to download the remote SQL ZIP file.');
    }

    // 解压 SQL ZIP 文件并获取 SQL 文件
    $zip = new ZipArchive();
    if ($zip->open($tempZip) === TRUE) {
        $sqlFile = $zip->getNameIndex(0);
        $zip->extractTo(sys_get_temp_dir());
        $zip->close();
    } else {
        throw new Exception('Failed to extract the SQL ZIP file.');
    }

    // 清空数据库
    $dsn = "mysql:host=$dbHost;dbname=$dbName";
    $pdo = new PDO($dsn, $dbUser, $dbPassword);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    foreach ($tables as $table) {
        $pdo->exec("DROP TABLE IF EXISTS `$table`");
    }
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");

    // 导入 SQL 数据
    $pdo->exec(file_get_contents(sys_get_temp_dir() . '/' . $sqlFile));

    // 删除临时文件
    unlink($tempZip);
    unlink(sys_get_temp_dir() . '/' . $sqlFile);
}

How to use it:

try {
    importSqlZip('http://example.com/backup.sql.zip', 'localhost', 'mydatabase', 'myusername', 'mypassword');
    echo 'Import success!';
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

 

 
微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232
PHP special character escaping and restoration

PHP special character escaping and restoration Language Notes PHP PHP collection PHP and mysql

Escape character is a special character constant. Escape characters are backslashed " & quot; At the beginning, followed by one or more characters. The escaped character has a specific meaning, which is different from the original meaning of the character, so it is called "escaped" character. The use of escape characters 1: turn ordinary characters into special purposes, such as back key and enter key. 2. Used to convert a character with special meaning back to its original meaning. 3. Before data is written into the database, escape characters (function …
👁 180
mysqli in PHP

mysqli in PHP Language Notes PHP PHP collection PHP and mysql

The `mysqli_num_rows()` function is exclusively used with `SELECT` query methods, whereas the `mysqli_affected_rows()` function returns the number of rows affected by the previous SQL statement across the entire database; this function is primarily used with `INSERT`, `UPDATE`, and `DELETE` operations.
👁 146

Recommended reading

Security Monitoring Website Template 1035

Security Monitoring Website Template 1035 Practical Collection Yiyou template

This EyouCMS template is ideal for the security and surveillance industry, featuring a modern, technology-driven design that effectively showcases surveillance equipment, security systems, solutions, and project cases. It enables security technology companies to present their products online and attract both commercial and government clients. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (E...
👁 48
EyouCMS (EyouCms) system installation tutorial

EyouCMS (EyouCms) system installation tutorial Program Notes Yiyoucms

1. System Overview Eyou Content Management System (EyouCms) is an enterprise-level open source website building system developed based on PHP+MySQL architecture, using ThinkPHP 5.0 as the underlying framework. 2. Environmental requirements Before installing EyouCms, please ensure that the server environment meets the following requirements: Project requirements operating system Linux/Unix/WindowsWeb server Nginx/…
👁 59
(Adaptive Mobile App) – APP Download Site; pbootCMS Template – HTML5 Responsive Mobile App Download Website Source Code – 0183

(Adaptive Mobile App) – APP Download Site; pbootCMS Template – HTML5 Responsive Mobile App Download Website Source Code – 0183 Practical Collection pbootcms Template

This set of PbootCMS templates for adaptive mobile apps and software download sites utilizes HTML5 responsive technology. The clean and efficient design is ideal for showcasing various mobile applications, games, and tutorial resources, helping software download sites or app stores attract online traffic and users. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s...
👁 49
Smart parking lot barrier equipment corporate website template 1036

Smart parking lot barrier equipment corporate website template 1036 Practical Collection Yiyou template

An eyoucms website template for smart parking lots and gate equipment companies. The design style is technological and safe, and can display parking systems, gate equipment, intelligent management solutions and engineering cases. It helps smart security companies display their products online and attract property and commercial customers. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Yiyou CMS installation common...
👁 43
Common sense of life popular information website template 0002

Common sense of life popular information website template 0002 Practical Collection Yiyou template

This set of eyoucms templates is specially created for daily life knowledge and popular information websites. The design style is simple and clear, and the information hierarchy is clear. It is suitable for building a comprehensive information platform such as life encyclopedia, health knowledge, and practical tips, helping content creators to quickly launch a user-friendly information sharing station. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Yiyou CMS installation...
👁 32
(Adaptive mobile phone version) HTML5 responsive APP application software download pbootcms website template Mobile application tutorial website source code download 0184

(Adaptive mobile phone version) HTML5 responsive APP application software download pbootcms website template Mobile application tutorial website source code download 0184 Practical Collection pbootcms Template

An adaptive mobile phone HTML5 responsive APP application software download PbootCMS website template. The design style is modern and technological, suitable for displaying APP application introduction, download links and usage tutorials. It is an excellent tool for application developers or promotion channels to build download pages with high conversion rates. Template display Installation instructions Website backend:/admin.php Account: admin Password: admin Unzip password: www.4…
👁 41