Hongmu Notes
Home Language Notes After PHP uploads the sql file, clear the mysql database and then import the sql file
Language Notes PHP PHP and mysql

After PHP uploads the sql file, clear the mysql database and then import the sql file

After PHP uploads the sql file, clear the mysql database and then import the sql file

Very practical feature!

PHP code:

 隐藏内容:登录后可查看
<?php
// 连接到 MySQL 数据库
$host = "localhost";        // MySQL 服务器地址
$username = "your_username"; // MySQL 用户名
$password = "your_password"; // MySQL 密码
$dbname = "your_database";   // MySQL 数据库名
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 上传文件
if (isset($_FILES["file"]) && $_FILES["file"]["error"] == 0) {
    $target_dir = "/path/to/upload/directory/"; // 修改为你的上传目录
    $target_file = $target_dir . basename($_FILES["file"]["name"]);
    $fileType = pathinfo($target_file, PATHINFO_EXTENSION);
    $allowedTypes = array('sql'); // 仅允许上传 SQL 文件
    if (in_array($fileType, $allowedTypes)) {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            // 清空数据库
            $tables = $conn->query("SHOW TABLES")->fetch_all();
            foreach ($tables as $table) {
                $conn->query("DROP TABLE IF EXISTS {$table[0]}");
            }

            // 导入 SQL 文件
            $sql = file_get_contents($target_file);
            if ($conn->multi_query($sql)) {
                echo "SQL 文件成功导入到数据库。";
            } else {
                echo "导入 SQL 文件时发生错误:" . $conn->error;
            }
        } else {
            echo "上传文件失败。";
        }
    } else {
        echo "只允许上传 SQL 文件。";
    }
} else {
    echo "请选择要上传的文件。";
}

// 关闭数据库连接
$conn->close();
?>

Please place $host$username$password$dbname$target_dir Replace with your actual information. The uploaded SQL file must be stored in $target_dir The directory is used exclusively for uploading SQL files; if no errors occur during the upload and import process, the database will be cleared and the SQL file will be imported.

Note: In production environments, for security reasons, uploaded files should undergo additional validation and filtering – for example, by restricting the allowed file types and sizes to prevent file upload vulnerabilities.

HTMLform:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Upload SQL File</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-g5AX/vyqo5KOGxz5AAn/AY1dRItbsdw7tHtzNjh9avsgzP0nckdKP/Jc1wJfONjK" crossorigin="anonymous">
  </head>
  <body>
    <div class="container">
      <h1>Upload SQL File</h1>
      <form action="upload_sql.php" method="post" enctype="multipart/form-data">
        <div class="form-group">
          <label for="sqlFile">Select SQL File</label>
          <input type="file" class="form-control-file" id="sqlFile" name="sqlFile">
        </div>
        <button type="submit" class="btn btn-primary">Upload</button>
      </form>
    </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@2.9.3/dist/umd/popper.min.js" integrity="sha384-lb6U1+A6OHXWnogQIgUpkzwFJa5yk5PbRyfPYpV1FaaLnNm/KTMc2QH8Heq7ZjKd" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-LpW1aXBBv/smfihSkStFCTyJf35QLlAdAGl7Yh2i2IDJnVWj9X3v7FJITgG14x7V" crossorigin="anonymous"></script>
  </body>
</html>

Please note that this form contains only a single file input field and a submit button; you can use it to upload an SQL file and submit it to a destination named upload_sql.php Processing script: You need to modify the form element names and the target of the submission operation according to your actual requirements.

When the two are combined – for example:

 隐藏内容:会员可查看
<?php
if($_FILES['sqlFile']){
// 连接到 MySQL 数据库
$host = "localhost";        // MySQL 服务器地址
$username = "test_4s5_cn"; // MySQL 用户名
$password = "wnxxtJTa3y4SPPrr"; // MySQL 密码
$dbname = "test_4s5_cn";   // MySQL 数据库名
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 上传文件
if (isset($_FILES["sqlFile"]) && $_FILES["sqlFile"]["error"] == 0) {
    $target_dir = __DIR__."/path/"; // 修改为你的上传目录
    // 创建指定目录
    if (!mkdir($target_dir, 0777, true)) {
        throw new Exception('Failed to create directory.');
    }
    $target_file = $target_dir . basename($_FILES["sqlFile"]["name"]);
    $fileType = pathinfo($target_file, PATHINFO_EXTENSION);
    $allowedTypes = array('sql'); // 仅允许上传 SQL 文件
    if (in_array($fileType, $allowedTypes)) {
        if (move_uploaded_file($_FILES["sqlFile"]["tmp_name"], $target_file)) {
            // 清空数据库
            $tables = $conn->query("SHOW TABLES")->fetch_all();
            foreach ($tables as $table) {
                $conn->query("DROP TABLE IF EXISTS {$table[0]}");
            }

            // 导入 SQL 文件
            $sql = file_get_contents($target_file);
            if ($conn->multi_query($sql)) {
                echo "SQL 文件成功导入到数据库。";
            } else {
                echo "导入 SQL 文件时发生错误:" . $conn->error;
            }
        } else {
            echo "上传文件失败。";
        }
    } else {
        echo "只允许上传 SQL 文件。";
    }
} else {
    echo "请选择要上传的文件。";
}
if (is_dir($target_dir)) { // 如果目录存在
    $files = glob($target_dir . '/*'); // 获取目录下的所有文件和子目录
    foreach ($files as $file) {
        if (is_file($file)) { // 如果是文件则直接删除
            unlink($file);
        } else { // 如果是子目录则递归调用自身
            deleteDir($file);
        }
    }
    rmdir($target_dir); // 删除目录
}

// 关闭数据库连接
$conn->close();
}
?>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Upload SQL File</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-g5AX/vyqo5KOGxz5AAn/AY1dRItbsdw7tHtzNjh9avsgzP0nckdKP/Jc1wJfONjK" crossorigin="anonymous">
  </head>
  <body>
    <div class="container">
      <h1>Upload SQL File</h1>
      <form action="<?=$SERVER['SCRIPT_NAME']?>" method="post" enctype="multipart/form-data">
        <div class="form-group">
          <label for="sqlFile">Select SQL File</label>
          <input type="file" class="form-control-file" id="sqlFile" name="sqlFile">
        </div>
        <button type="submit" class="btn btn-primary">Upload</button>
      </form>
    </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@2.9.3/dist/umd/popper.min.js" integrity="sha384-lb6U1+A6OHXWnogQIgUpkzwFJa5yk5PbRyfPYpV1FaaLnNm/KTMc2QH8Heq7ZjKd" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-LpW1aXBBv/smfihSkStFCTyJf35QLlAdAGl7Yh2i2IDJnVWj9X3v7FJITgG14x7V" crossorigin="anonymous"></script>
  </body>
</html>

微信赞赏

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 …
👁 181
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

(Adaptive Mobile Version) Responsive Precision Mechanical Mold Category PBootCMS Website Template – Download Website Source Code for Precision Instrument Mold Machining Equipment – 0161

(Adaptive Mobile Version) Responsive Precision Mechanical Mold Category PBootCMS Website Template – Download Website Source Code for Precision Instrument Mold Machining Equipment – 0161 Practical Collection pbootcms Template

This is an adaptive, mobile-friendly, responsive PbootCMS website template designed for precision mechanical mold applications. Its professional and sophisticated design is ideal for showcasing precision molds, machining equipment, and manufacturing processes. It enables mold manufacturing enterprises to demonstrate their high-precision manufacturing capabilities online and attract customers from industries such as automotive and electronics. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s...
👁 60
Responsive children's educational toy website template 0992

Responsive children's educational toy website template 0992 Practical Collection Yiyou template

An eyouCMS responsive website template designed for the children's educational toy industry. Its vibrant and playful design is perfect for showcasing educational toy products, educational philosophies, brand stories, and safety standards. This template helps toy brands showcase their products online and attract both parents and children. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for YouYouCMS | YouYouCMS...
👁 35
(Adaptive Mobile Version) Travel Guide Website Template – Article/Blog Website Source Code – With Comment Feature – 1142

(Adaptive Mobile Version) Travel Guide Website Template – Article/Blog Website Source Code – With Comment Feature – 1142 Practical Collection pbootcms Template

A PbootCMS website template designed for travel guides and blog posts, compatible with both PC and WAP devices, and featuring a comment section. Its fresh, travel-themed design makes it ideal for travel enthusiasts to share their travel stories, guides, and photography. The comment feature enhances user interaction and helps foster a community atmosphere. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 65
(Adaptive Mobile Version) Responsive Red Mechanical Hardware Website – PBootCMS Template; Download Source Code for Heavy Industry Steel and Machinery Enterprise Website Templates – 0162

(Adaptive Mobile Version) Responsive Red Mechanical Hardware Website – PBootCMS Template; Download Source Code for Heavy Industry Steel and Machinery Enterprise Website Templates – 0162 Practical Collection pbootcms Template

An adaptive, mobile-friendly responsive red mechanical hardware PbootCMS website template designed for the heavy industry and steel machinery sectors. Its dynamic yet professional design effectively showcases large-scale machinery, steel products, and industrial environments. This template helps heavy-industry enterprises build a strong online brand presence and attract customers within the industrial sector. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password:...
👁 27
Responsive International Freight Logistics Industry Website Template 0993

Responsive International Freight Logistics Industry Website Template 0993 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the international freight logistics industry. Its efficient, modern design effectively showcases the company's logistics service network, freight solutions, and corporate strength, helping international logistics firms attract cross-border trade clients online. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (Eyou...
👁 57
(PC+WAP) Cable Coil Website Template – Download Plastic Cable Coil Website Source Code – 1143

(PC+WAP) Cable Coil Website Template – Download Plastic Cable Coil Website Source Code – 1143 Practical Collection pbootcms Template

A cable reel and plastic reel website template (PbootCMS), compatible with both PC and WAP devices. The professional industrial design is ideal for showcasing cable reel products, plastic products, and industrial applications. It enables cable reel manufacturers to display their products online and attract clients in the power and telecommunications sectors. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 46