使用PDO PHP将CSV导入MySQL数据库

时间:2018-04-29 13:48:25

标签: php mysql csv pdo

我正在尝试创建一个sql注入安全的表单,您可以将CSV文件上传到MySQL数据库。我的代码如下所示,它回显了浏览器中csv中的数据,但没有将数据插入数据库。

<?php
require_once("session.php");
require_once("class.user.php");
$user = new USER();
$user_id = $_SESSION['user_session'];

if(isset($_SESSION['user_session']))
{
    if (isset($_POST['submit'])) {
        $session = $_SESSION['user_session'];
        //upload file
        if (is_uploaded_file($_FILES['csv']['tmp_name'])) {
            echo "<h1>" . "File ". $_FILES['csv']['name'] ." uploaded successfully." . "</h1>";
            echo "<h2>Displaying contents:</h2>";
            readfile($_FILES['csv']['tmp_name']);
        }
        //Import uploaded file to Database
        $handle = fopen($_FILES['csv']['tmp_name'], "r");
        $stmt = $user->runQuery("INSERT INTO main(
                first_name,
                last_name,
                info1,
                info2,
                info3,
                info4,
                info5,
                info6,
                info7,
                info8) VALUES(
                ?,?,?,?,?,?,?,?,?,?)");
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $stmt->bindparam(1, $data[0], PDO::PARAM_STR);
            $stmt->bindparam(2, $data[1], PDO::PARAM_STR);
            $stmt->bindparam(3, $data[2], PDO::PARAM_STR);
            $stmt->bindparam(4, $data[3], PDO::PARAM_STR);
            $stmt->bindparam(5, $data[4], PDO::PARAM_STR);
            $stmt->bindparam(6, $data[5], PDO::PARAM_STR);
            $stmt->bindparam(7, $data[6], PDO::PARAM_STR);
            $stmt->bindparam(8, $data[7], PDO::PARAM_STR);
            $stmt->bindparam(9, $data[8], PDO::PARAM_STR);
            $stmt->bindparam(10, $data[9], PDO::PARAM_STR);
            $stmt->execute();
        }
        fclose($handle);
    }
}

?>

1 个答案:

答案 0 :(得分:-1)

删除了所有->bindParam并替换为->execute($data)