我正在尝试为MySQL文件设置导入/导出到MySQL。我有大部分,但我正在尝试验证信息。当我验证时,我不想将任何记录导入MySQL。我目前拥有的代码只会在空字段后才导入任何记录。我通常不会问,但我很难过。
app.use(function * setUserInContext (next) {
this.user = this.req.user
yield next
})
答案 0 :(得分:0)
好的,让我们看看:
// here you get an array from csv-string
while(($fileop = fgetcsv($handle,1000,",")) !==false){
// first: use trim function to remove spaces from left and right of a value
$first = trim($fileop[0]);
$last = trim($fileop[1]);
$birthday = trim($fileop[2]);
$age = trim($fileop[3]);
$address = trim($fileop[4]);
// now you have five values.
// u want to insert them to database only if they are ALL not empty
// use function empty to check if value is empty
if (!empty($first)
&& !empty($last)
&& !empty($birthday)
&& !empty($age)
&& !empty($address)
) {
$sql = mysqli_query($conn,"INSERT INTO `mytable` (first, last, birthday, age, address) VALUES ('$first','$last','$birthday','$age','$address')");
// other code here
}
}
此脚本将插入非空的值。但它仍会忽略空值的行。 如果你想检查你的csv的所有行中的所有字段是否都不为空,那么你应该这样做:
// set a special flag
$empty_value_found = false;
while(($fileop = fgetcsv($handle,1000,",")) !==false){
// first: use trim function to remove spaces from left and right of a value
$first = trim($fileop[0]);
$last = trim($fileop[1]);
$birthday = trim($fileop[2]);
$age = trim($fileop[3]);
$address = trim($fileop[4]);
// now you have five values.
// if any of them is empty - we should NOT go further and stop our cycle
if (empty($first)
|| empty($last)
|| empty($birthday)
|| empty($age)
|| empty($address)
) {
$empty_value_found = true;
break; // stop our while-loop
}
}
// now we check - if there no empty values
if (!$empty_value_found) {
// we can go through our file again and insert values,
// code is similar to what you have
}
所以,如果你想检查