gpt4 book ai didi

php - 在插入之前验证 CSV 数据的有效性以及 CSV 文件名,如果中间存在错误/丢失数据,则不要插入到数据库

转载 作者:行者123 更新时间:2023-11-29 18:40:36 25 4
gpt4 key购买 nike

我需要有关在插入之前验证 CSV 数据以及 CSV 文件名的帮助,如果中间存在错误/丢失数据,请勿插入到数据库并打印错误消息。

try {
if(isset($_POST['importSubmit'])){
//validate whether uploaded file is a csv file
$csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
$surveydate = $_POST['surveydate'];
$userID = $_SESSION['userID'];

if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
if(is_uploaded_file($_FILES['file']['tmp_name'])){
//open uploaded csv file with read only mode
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');

//skip first line
fgetcsv($csvFile);

//parse data from csv file line by line
while(($line = fgetcsv($csvFile)) !== FALSE) {
//check whether member already exists in database with same email
//insert member data into database
$db->query("INSERT INTO communitysurvey (surveyNum,stationID,age,gender,educationalattainment,question,response,userID,surveydate) VALUES('".$line[0]."', '".$line[1]."','".$line[2]."', '".$line[3]."', '".$line[4]."','".$line[5]."','".$line[6]."','{$userID}','{$surveydate}')");
}

//problem on userID session won't get inserted
//close opened csv file
fclose($csvFile);
}
}
}

//redirect to the listing page
header("Location: inputcommunity.php".$qstring);
} catch (Exception $e) {
alert ($e->getMessage());
}

最佳答案

要从 CSV 中获取数据,您可以使用 explode并在 while 循环中读取的每一行中爆炸分隔符(对于 CSV,可能是“,”或“,”)。这将返回该行中每个值的数组。您可以检查该数组的长度是否缺少值,并将类型/值与预期的类型/值进行比较以检查“正确性”。

关于php - 在插入之前验证 CSV 数据的有效性以及 CSV 文件名,如果中间存在错误/丢失数据,则不要插入到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44970273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com