Search code examples
phpmysqlexcelimport-from-excel

How can you specify from which column position to start the data import from excel to mysql


Hi guys i have an php excel issue. The problem is that i have an excel file that has several rows and columns, the deal is that i want to import only from specific row position for example A11 or C12. How can i tell this in php? Here is the column selection code:

    $csv_file = $a; 

if (($getfile = fopen($csv_file, "r")) !== FALSE) {

    while(! feof($getfile))
  {
    $data = fgetcsv($getfile, NULL,"\t");
    $col1 = $data[0];
    $col2 = $data[1];
    $col3 = $data[2];
     $col4 = $data[3];
     $col5 = $data[4];
     $col6 = $data[5];
     $col7 = $data[6];
     $col8 = $data[7];

     $query = "INSERT INTO $tableName(cod, den_material, furnizor, cant_reper ,lg, cod_furnizor, obs, data) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."')";
    $s=mysql_query($query);
}

Here is the full code:

<?php
if ($_FILES["file"]["error"] > 0)
{
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 10240) . " Kb<br>";
    //echo "Stored in: " . $_FILES["file"]["tmp_name"];
    $a=$_FILES["file"]["tmp_name"];
    //echo $a;
    $tableName = str_replace('.txt','',$_FILES["file"]["name"]);    

    $connect = mysql_connect('localhost','root','password');

if (!$connect) {
    die('Could not connect to MySQL: ' . mysql_error());
}   
//your database name
$cid =mysql_select_db('database_test',$connect);
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))!=1){
    $table = mysql_query("CREATE TABLE `$tableName` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `cod` TEXT NOT NULL,
    `den_material` TEXT NOT NULL,
    `furnizor` VARCHAR(255) NOT NULL,
    `cant_reper` VARCHAR(255) NOT NULL,
    `lg` VARCHAR(255) NOT NULL,
    `cod_furnizor` VARCHAR(255) NOT NULL,
    `obs` TEXT(255) NOT NULL,
    `data` DATE ,
    PRIMARY KEY (`id`)
    );");

    if(!$table){
        die("Upload failed");
    }
}



// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\xampp\htdocs -->
// Name of your CSV file
$csv_file = $a; 

if (($getfile = fopen($csv_file, "r")) !== FALSE) {

    while(! feof($getfile))
  {
    $data = fgetcsv($getfile, NULL,"\t");
    $col1 = $data[0];
    $col2 = $data[1];
    $col3 = $data[2];
     $col4 = $data[3];
     $col5 = $data[4];
     $col6 = $data[5];
     $col7 = $data[6];
     $col8 = $data[7];

     $query = "INSERT INTO $tableName(cod, den_material, furnizor, cant_reper ,lg, cod_furnizor, obs, data) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."')";
    $s=mysql_query($query);
}


}

echo "<script>alert('Data succesfully added!');window.location.href='index.php';</script>";
//echo "File data successfully imported to database!!";

}
?>

Hope you cand help me, thanks in advance! :)


Solution

  • Fair warning: I have never used fgetcsv for anything however I understand the principle.

    However working from the manual on php.net I have created a loop that starts reading only at the row and col that are specified. I picked random values but you can make them whatever you want. A=0, B=1 and so forth. So I have said something like all data from row 5 and from col C.

    <?php
    $row = 1;
    $mydata = array();
    $wantrow = 4;
    $wantcol = 2;
    if (($handle = fopen("test.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data); // number of fields in the line
            $row++;
            for ($c=0; $c < $num; $c++) {
                if($c<$wantcol){
                    // this is what we do not want
                }elseif($row<$wantrow){
                    // also we do not want this
                }else{
                    // ah-ha, we do want this
                    $mydata[$row][$c] = $data[$c];
                }
    
            }
        }
        fclose($handle);
    }
    ?>
    

    You would then have a two dimensional array of the values in that section. I have chosen to be a little clumsy looking so you can easily understand the logic of what I am trying to demonstrate.

    Actually you could make it fair more readable like this:

    if( ($c>=3) && ($row>=5) ){
        $mydata[$row][$c] = $data[$c];
    }
    

    You could apply further limits with the if statements and set an upper limit too but I am sure you know how to do that.

    if( ($c>=3) && ($c<=22) && ($row>=5) && ($row<=6) ){
        $mydata[$row][$c] = $data[$c];
    }
    

    This would give you square inside of C6 to E23 only.

    Also in you application you probably want to do something more useful than just shoving the data into an array. I imagine you probably want to embed the data into SQL or something like that.

    YYMV. I have not tested this code but it would be roughly like that.