我有一个 CSV 文件,其中有一列的日期格式为 d/m/Y,或者里面的单词“Illimité”在法语中表示无限。
我希望每次它读取“Illimité”时都将 NULL 值放入 MySQL 表中。
这是我当前的 PHP 代码:
if (isset($_POST['submit'])) {
$query = "TRUNCATE TABLE `formation` ";
$result = mysql_query($query);
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
while (($fileop = fgetcsv($handle, 1000, ";")) !== false) {
$nom = $fileop[0];
$prenom = $fileop[1];
$formation = $fileop[16];
$validite = $fileop[26];
if (is_numeric($validite)) {
$validite = date_format(date_create_from_format('d/m/Y', $validite), 'Y-m-d');
$sql = mysql_query("INSERT INTO formation (nom,prenom,formation,validite,usermaj) VALUES ('$nom','$prenom','$formation','$validite','importCSV')");
} else {
$sql = mysql_query("INSERT INTO formation (nom,prenom,formation,validite,usermaj) VALUES ('$nom','$prenom','$formation',NULL,'importCSV')");
}
}
很遗憾,这不起作用。 MySql 没有显示任何错误,并且始终为 NULL。 如有任何帮助,我将不胜感激。
最佳答案
试试这个:
function myFunc($CSVValue){
if(validateDate($CSVValue)){
//your mysql logic where you put in the date
}else{
//your mysql logic where you put in the null
}
}
function validateDate($date)
{
$d = DateTime::createFromFormat('d/m/Y', $date);
return $d && $d->format('d/m/Y') == $date;
}
-- 更新--
除了您提供的内容外,我不知道您的代码看起来如何。 如果你把它放在你的代码中,它可能看起来像这样:
if (isset($_POST['submit'])) {
$query = "TRUNCATE TABLE `formation` ";
$result = mysql_query($query);
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
while (($fileop = fgetcsv($handle, 1000, ";")) !== false) {
$nom = $fileop[0];
$prenom = $fileop[1];
$formation = $fileop[16];
$validite = $fileop[26];
$d = DateTime::createFromFormat('d/m/Y', $validite);
if ($d && $d->format('d/m/Y') == $validite) {
$validite = date_format(date_create_from_format('d/m/Y', $validite), 'Y-m-d');
$sql = mysql_query("INSERT INTO formation (nom,prenom,formation,validite,usermaj) VALUES ('$nom','$prenom','$formation','$validite','importCSV')");
} else {
$sql = mysql_query("INSERT INTO formation (nom,prenom,formation,validite,usermaj) VALUES ('$nom','$prenom','$formation',NULL,'importCSV')");
}
}
关于php - 导入包含日期或文本列的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29841010/