0

I'm trying to import data through files and below code works fine with csv files but, when I upload a zip file it uploads some garbage value into database. Can you please help me with this. Thank you!

<?php

include_once 'dbConfig.php';

if(isset($_POST['importSubmit'])){

$csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet- 
stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain', 'application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');

if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){
    
    if(is_uploaded_file($_FILES['file']['tmp_name'])){
        
        $csvFile = fopen($_FILES['file']['tmp_name'], 'r');
        
        fgetcsv($csvFile);
        
        while(($line = fgetcsv($csvFile)) !== FALSE){
            $name   = $line[0];
            $email  = $line[1];
            
            $prevQuery = "SELECT id FROM members WHERE email = '".$line[1]."'";
            $prevResult = $db->query($prevQuery);
            
            if($prevResult->num_rows > 0){
                $db->query("UPDATE members SET name = '".$name."', modified = NOW() WHERE email = '".$email."'");
            }else{
                $db->query("INSERT INTO members (name, email) VALUES ('".$name."', '".$email."')");
            }
        }
        
        fclose($csvFile);
        
        $qstring = '?status=succ';
    }else{
        $qstring = '?status=err';
    }
}else{
    $qstring = '?status=invalid_file';
}
}

header("Location: index1.php".$qstring);

?>
7
  • You need to unzip the file first php.net/manual/en/class.ziparchive.php Commented Mar 21, 2021 at 5:09
  • hi @bassxzero but what destination path I should give it for extracted file Commented Mar 21, 2021 at 5:19
  • Whatever writable path you have set on you server. Try /tmp or check the path that your files are being uploaded to. echo $_FILES['file']['tmp_name'] Commented Mar 21, 2021 at 5:23
  • Actually you don't have to write the file to storage. You can hold it in memory and iterate through it for your queries. Commented Mar 21, 2021 at 5:26
  • thanks for the help @bassxzero but how can I hold it in memory and iterate it? Commented Mar 21, 2021 at 5:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.