简体   繁体   中英

skip specific rows and columns of csv with PHP

Hi I would like to know how can I skip certain colums/rows from a csv. I have a form that uploads a cvs to MySQL and works fine, I also know how to skip the first line of the csv, but the format of the file I need to upload seems pretty hard for me. This is my code:

<body>

<div class="container">

[enter image description here][1]<?php
if(isset($_POST['uploadBtn'])){
    $fileName=$_FILES['myFile']['name'];
    $fileTmpName=$_FILES['myFile']['tmp_name'];
    //FILE PATH
    $fileExtension=pathinfo($fileName,PATHINFO_EXTENSION);
    //ALLOWED FILE TYPES
    $allowedType = array('csv');
    if(!in_array($fileExtension,$allowedType)){?>

        <div class="alert alert-danger">
            INVALID FILE
        </div>
    <?php }else{

        $handle = fopen($fileTmpName, 'r');
        fgetcsv($handle);///////////////// SKIP FIRST ROW
        while (($myData = fgetcsv($handle,1000,','))!== FALSE){
                $name = $myData[0];
                $email = $myData[1];

                $query = "INSERT INTO databse.excel_table (name,email)
                VALUES ('".$name."','".$email."')";
                $run = mysql_query($query);

        }
        if(!$run){
            die("error in uploading file".mysql_error());
        }else{ ?>
                <div class="alert alert-success">
                    SUCCESS
                </div>
    <?php   }
    }
}
    ?>

<form action="" method="post" enctype="multipart/form-data">
    <h3 class="text-center">
        RESULTS
    </h3></hr>
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <input type="file" name="myFile" class="form-control">
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <input type="submit" name ="uploadBtn" class="btn btn-info">
            </div>
        </div>
    </div>
</form>
</div>
</body>
</html>

Thanks in advance. example of csv

Count the lines and skipp all lines before 14th one.

    <body>

    <div class="container">
<?php
    if(isset($_POST['uploadBtn'])){
        $fileName=$_FILES['myFile']['name'];
        $fileTmpName=$_FILES['myFile']['tmp_name'];
        //FILE PATH
        $fileExtension=pathinfo($fileName,PATHINFO_EXTENSION);
        //ALLOWED FILE TYPES
        $allowedType = array('csv');
        if(!in_array($fileExtension,$allowedType)){?>

            <div class="alert alert-danger">
                INVALID FILE
            </div>
        <?php }else{

            $handle = fopen($fileTmpName, 'r');
            fgetcsv($handle);///////////////// SKIP FIRST ROW
            $k = 0;
            while (($myData = fgetcsv($handle,1000,','))!== FALSE){
             $k++;
              if ( $k > 14 ) {

                    $name = $myData[0];
                    $email = $myData[1];

                    $query = "INSERT INTO databse.excel_table (name,email)
                    VALUES ('".$name."','".$email."')";
                    $run = mysql_query($query);
                 }

            }
            if(!$run){
                die("error in uploading file".mysql_error());
            }else{ ?>
                    <div class="alert alert-success">
                        SUCCESS
                    </div>
        <?php   }
        }
    }
        ?>

    <form action="" method="post" enctype="multipart/form-data">
        <h3 class="text-center">
            RESULTS
        </h3></hr>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <input type="file" name="myFile" class="form-control">
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <input type="submit" name ="uploadBtn" class="btn btn-info">
                </div>
            </div>
        </div>
    </form>
    </div>
    </body>
    </html>

Using your loop, here is a way to pull that off.

USE ONE OF THESE NOT BOTH.

$rowsToSkip = [0,3,6,9]; //this is one way to manually enter row numbers
$rowsToSkip = range(5,10) //will return an array ex: [5,6,7,8,9,10]

AND SETUP YOUR LOOP

$i = 0; //this is used to keep an track of what row you are on
while (($myData = fgetcsv($handle,1000,','))!== FALSE){
  if($i == 0) continue; //this will skip your 1st row
  if(in_array($i, $rowsToSkip)) continue; //this will skip any row in $rowsToSkip array

  $name = $myData[0];
  $email = $myData[1];

  $query = "INSERT INTO databse.excel_table (name,email)
  VALUES ('".$name."','".$email."')";
  $run = mysql_query($query);
}

2 SUGGESTIONS / HELPFUL BUT NOT NEEDED TO GET THIS WORKING

  • Don't query in any for/while/each, its better to put the string together first then query once.

  • Don't use mysql, its old and insecure. USE PDO or mysqli instead

Your loop again

$i = 0; //this is used to keep an track of what row you are on
$values = []; //will hold your row values
while (($myData = fgetcsv($handle,1000,','))!== FALSE){
  if($i == 0) continue; //this will skip your 1st row
  if(in_array($i, $rowsToSkip)) continue; //this will skip any row in $rowsToSkip array

  $name = $myData[0];
  $email = $myData[1];

  $values[] = "('".$name."','".$email."')";
}

take the query out of the loop, use implode to add the values in later

$query = "INSERT INTO databse.excel_table (name,email) VALUES (". implode("," , $values) .")";
$run = mysql_query($query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM