如果csv中的列小于或大于4,如何发出警告并且不继续执行命令?我有这段代码可以导入csv,但是我只需要4列即可避免将值不必要地插入到mysql中
while(($csvdata = fgetcsv($handle,10000,","))!== FALSE){
if($i>0) {
$sha1 = $csvdata[0];
$vsdt = $csvdata[1];
$trendx = $csvdata[2];
$notes = $csvdata[3];
// Get record where sha1
$check_sha = "SELECT sha1 FROM jeremy_table_test WHERE sha1='".$sha1."'";
$check_shaquery = mysqli_query($con , $check_sha);
if($check_shaquery){
$sha_count = mysqli_num_rows($check_shaquery);
}
// Check if sha1 already in database
if(isset($sha_count) && $sha_count>0){
$sql = "UPDATE `jeremy_table_test` SET `date_sourced`='".$date."',`sha1`='".$sha1."',`vsdt`='".$vsdt."',`trendx`='".$trendx."',`notes`='".$notes."' WHERE sha1='".$sha1."'";
$query = mysqli_query($con , $sql);
}else{
$sql = "INSERT INTO jeremy_table_test (date_sourced,sha1,vsdt,trendx,notes) VALUES ('$date','$sha1','$vsdt','$trendx','$notes')";
$query = mysqli_query($con , $sql);
}
$c = $c+1;
error_reporting(E_ALL ^ E_NOTICE);
}
$i++;
error_reporting(E_ALL ^ E_NOTICE);
}
请给我一些有关如何执行此操作的想法。这是我唯一的问题
答案 0 :(得分:1)
您只需要在while {..}
循环的开始使用count()
函数。
while(($csvdata = fgetcsv($handle,10000,","))!== FALSE){
// If count of the array is not equal to 4
if ( count($csvdata) !== 4 ) {
// Throw exception and exit.
throw new Exception("Invalid CSV file. Column count not matching!");
exit();
}
....