php 如何使用html按钮导入数据库sql/csv文件?

blmhpbnm  于 2023-05-05  发布在  PHP
关注(0)|答案(1)|浏览(171)

如何使用html按钮导入数据库文件?
我试图创建一个上传按钮,并试图从数据库上传导入的sql文件,但数据不去数据库

<?php
require "../database.php";

if(isset($_POST['submit'])) {
    $sql_file = $_POST['data'];

    // Read SQL file
    $sql = file_get_contents($sql_file);

    // Execute SQL statements
    if (mysqli_multi_query($conn, $sql)) {
        echo "SQL file imported successfully";
    } else {
        echo "Error importing SQL file: ";
    }

    // Close database connection
    mysqli_close($conn);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import Database</title>
</head>
<body>
    <?php include '../navigation.php';?>

    <div class="container-lg">
    <form action="import.php" method="post">
        <input type="file" class="form-control mt-5" name="data">
        <button type="submit" class="btn btn-success" name="submit">Import Database</button>
    </form>
    </div>

</body>
</html>
this is my code
6vl6ewon

6vl6ewon1#

我认为你的第一个问题在定义SQL文件:$sql_file = $_POST['data'];用于定义必须使用的文件

<?php
    
        $conn =new mysqli('localhost', 'root', '' , 'blog_samples');
        
        $query = '';
        $sqlScript = file('database-script.sql');
        foreach ($sqlScript as $line)   {
            
            $startWith = substr(trim($line), 0 ,2);
            $endWith = substr(trim($line), -1 ,1);
            
            if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
                continue;
            }
            
    
    $query = $query . $line;
    if ($endWith == ';') {
        mysqli_query($conn,$query) or die('<div class="error-response sql-
        import-response">Problem in executing the SQL query <b>' . $query. '</b></div>');
                $query= '';     
            }
        }
    
        echo '<div class="success-response sql-import-response">SQL file imported successfully</div>';
        ?>

来自https://phppot.com/php/how-to-import-sql-into-a-database-using-php/的资源

相关问题