简体   繁体   English

使用PHP PDO从CSV从mysql插入数据

[英]Inserting data from mysql from CSV using PHP PDO

I have list of data in CSV and need to insert this data into a MySQL database. 我有CSV数据列表,需要将此数据插入MySQL数据库。 These data should be safely inserted ie sanitation. 这些数据应安全插入,即卫生。 So, I have used PDO object to rectify SQL injection. 因此,我使用了PDO对象来纠正SQL注入。 But, it fails to get data from CSV file and inserts null values. 但是,它无法从CSV文件获取数据并插入空值。

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? 谁能帮我解决这个问题?

If you take a look at the documentation for array_combine() you'll see that its purpose is to build an associative array. 如果看一下array_combine()的文档,您会发现它的目的是建立一个关联数组。 You use this function in csvToArray() but later in your code you are trying to get data using numeric keys. 您可以在csvToArray()使用此函数,但是稍后在代码中,您尝试使用数字键获取数据。 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. 很少需要单独绑定的参数,在几乎所有情况下,您都可以将数据作为数组提供给PDOStatement::execute() It's also bad form to store HTML entities in a database; 将HTML实体存储在数据库中也是一种不好的形式。 if you need to output to HTML, you perform escaping at that point. 如果您需要输出为HTML,则可以在此时进行转义。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM