CSV to database with php

。_饼干妹妹 提交于 2019-12-06 05:10:57
Parfait

Your fundamental issue is you do not specify the comma delimiter in the fgetcsv() function. As a result, all the data pushed into one column, date[0] and the Access ACE/JET engine unable to convert to date/time of the first column rendered all to zero which in unix time begins at 1/1/1970.

Also, consider using try/catch to catch PDO exceptions.

try {
      $import= $dbh->prepare("INSERT INTO adherence(
                              dateandtime,
                              lastname,
                              paidtime,
                              approvedtime,
                              notadhering) VALUES(
                              ?,?,?,?,?)");

    $i = 0;        
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

        if($i > 0) {
            $data = str_replace('"', '', $data); 

            $import->bindParam(1, $data[0], PDO::PARAM_STR);                
            $import->bindParam(2, $data[1], PDO::PARAM_STR);                
            $import->bindParam(3, $data[2], PDO::PARAM_STR);                
            $import->bindParam(4, $data[3], PDO::PARAM_STR);                
            $import->bindParam(5, $data[4], PDO::PARAM_STR);                
            $import->execute();
        }
        $i++;

    }
}

catch(PDOException $e) {  
    echo $e->getMessage()."\n";
}

As for dates, MS Access date/time field follows the current CPU's language clock such as MM/DD/YYYY (US) or DD/MM/YYYY (UK), etc. It does not follow the date/time format of other RDMS's of YYYY-MM-DD or such variants. So there is no need to convert since your csv aligned already to Access' format. With that being said, you may receive a warning:

SQLSTATE[22018]: Invalid character value for cast specification: -3030 

However, according to my tests, the database updated all rows correctly. Normally, you would concatenate the # around date strings which I tried to no avail with your code but possibly in your bind parameters process, string types do not wrap ideally with the hashtags.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!