dqqxkq4047 2018-10-23 16:07
浏览 150

使用PHP PDO从CSV插入mysql数据

I have list of data in CSV and need to insert this data into a MySQL database. These data should be safely inserted i.e sanitation. So, I have used PDO object to rectify SQL injection. But, it fails to get data from CSV file and inserts null values.

Here is the example,

<?php
$servername = "localhost";
$username   = "root";
$password   = "";

try {
    $conn = new PDO("mysql:host=$servername;dbname=contact_list",$username,$password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "connection successfully";
}
catch(PDOException $e)
{
    echo "connection Failed:" . $e -> getMessage();
}

// Create  CSV to Array function
function csvToArray($filename = '', $delimiter = ',')
{
    if (!file_exists($filename) || !is_readable($filename)) {
        return false;
    }

    $header = NULL;
    $result = array();
    if (($handle = fopen($filename, 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
            if (!$header)
                $header = $row;
            else
                $result[] = array_combine($header, $row);

        }
        fclose($handle);
    }

    return $result;
}

// Insert data into database   

$all_data = csvToArray('contact.csv');
foreach ($all_data as $data) {

    $data = array_map(function($row){
        return filter_var($row, FILTER_SANITIZE_STRING, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        }, $data);

    $sql = $conn->prepare("INSERT INTO contact 
                (title, first_name,last_name,company_name,date_of_birth,notes) 
        VALUES (:t, :fname, :lname,:cname,:dob,:note)");

    $sql->bindParam(':t', $data[1], PDO::PARAM_STR);
    $sql->bindParam(':fname', $data[2], PDO::PARAM_STR);
    $sql->bindParam(':lname', $data[3], PDO::PARAM_STR);
    $sql->bindParam(':cname', $data[0], PDO::PARAM_STR);
    $sql->bindParam(':dob', $data[4], PDO::PARAM_STR);
    $sql->bindParam(':note', $data[15], PDO::PARAM_STR);
    print_r($data);
    $sql->execute();    
}
?>

Can anyone help me to solve this?

  • 写回答

1条回答 默认 最新

  • dshfjsh_5455 2018-10-23 23:14
    关注

    If you take a look at the documentation for array_combine() you'll see that its purpose is to build an associative array. You use this function in csvToArray() but later in your code you are trying to get data using numeric keys. I wouldn't expect you'd ever have anything inserted.

    On a side note, you are completely defeating the purpose of prepared statements by repeatedly preparing the same statement over and over again. Prepare once and execute many times. Individually binding parameters is rarely needed, in almost all cases you can provide the data to PDOStatement::execute() as an array. It's also bad form to store HTML entities in a database; if you need to output to HTML, you perform escaping at that point.

    Something like this should work (adjust array key names as necessary.)

    $all_data = csvToArray('contact.csv');
    $sql = $conn->prepare("INSERT INTO contact 
        (title, first_name, last_name, company_name, date_of_birth, notes) 
        VALUES (:t, :fname, :lname,:cname,:dob,:note)");
    foreach ($all_data as $data) {
        $params = [
            ":t"     => $data["t"],
            ":fname" => $data["fname"],
            ":lname" => $data["lname"],
            ":dob"   => $data["dob"],
            ":note"  => $data["note"],
        ];
        $sql->execute($params);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器