检查csv中的列在给定的max中是>还是<

3zwtqj6y  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(339)

如果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);
    }

请告诉我怎么做。这是我唯一的问题

czq61nw1

czq61nw11#

你只需要使用 count() 在您的 while {..} 循环。

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();
    }

....

相关问题