PHP实现连接数据库下载与导入csv格式文件

<!--php代码-->
<?php
    //连接数据库
    $conn = mysqli_connect('localhost', 'root', '123456', 'student');

    //判断表单是否点击下载按钮
    if (isset($_POST['dow'])) {
        //请求下载代码
        header("Content-type: application/vnd.ms-excel; charset=utf-8");
        Header("Content-Disposition: attachment; filename=student.csv");
        //通过数据库连接查询所要下载的表信息
        $res = mysqli_query($conn, 'select number,name,sex,age from student join class on student.class=class.id order by number asc');
        if ($res && mysqli_num_rows($res) > 0) {
            while ($row = mysqli_fetch_assoc($res)) {
                $row['sex'] == '1' ? $row['sex'] = "男" : $row['sex'] = "女";
                $arr[] = $row;
            }
        }
        echo "学号,姓名,性别,年龄" . "
";
        foreach ($arr as $item) {
            echo implode(',', $item) . "
";
        };
        die;
    }

    //自定义一个数据插入数据库函数
    function add($table, $data)
    {
        global $conn;

        $sql = "INSERT INTO `$table`";

        $sql .= " (`" . implode("`,`", array_keys($data)) . "`)";

        $sql .= " VALUES ('" . implode("','", $data) . "')";

        $result = mysqli_query($conn, $sql);

        if ($result && mysqli_insert_id($conn) > 0) {
            return mysqli_insert_id($conn);
        } else {
            return 0;
        }
    };

    //判断是否点击提交上传按钮并且上传文件不为空
    if (isset($_POST['sub']) && !empty($_FILES['file'])) {
        //读取上传文件内容
        $con = file($_FILES['push']['tmp_name']);

        //去除字段名再重组新数组
        foreach ($con as $key => $item) {
            if ($key == 0) {
                continue;
            }
            $arr[] = explode(',', $item);
        }

        //去掉主键将数据保存为字段对应的关联数组
        foreach ($arr as $k => $v) {
            $arr[] = explode(',', $item);
            $arr1[$k] = [
                'name' => $v[1],
                'sex' => $v[2] == '男' ? '1' : '0',
                'age' => $v[3],
            ];
        }
       
        //遍历二维数组将得到的一维关联数组依次插入数据库
        foreach ($arr1 as $a) {
            $res = add('student', $a);
        }
        if ($res) {
            echo "<script>alert('导入数据成功!')</script>";
        } else {
            echo "<script>alert('导入数据失败!')</script>";
        }
    }
?>
<!--html代码-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    <button name="dow">点击下载</button>
    <input type="file" name="push" value="">
    <input type="submit" name="sub" value="上传数据">
</form>
</body>
</html>
原文地址:https://www.cnblogs.com/wxdindex/p/11264919.html