BStud BStud - 7 months ago 10
SQL Question

Zipping and downloading multiple files from multiple columns in mysql database

I have simple script like add-to-cart where I can put multiple files for later downloading. When user click on add to cart I store the ID of the file in session and when he click download all based on ID's stored it lookup into database table and download the files.

All the files are stored in same folder and I keep the names in table. The problem that I faced is that in the table I have 3 columns which hold different files(items). This is what I have so far and is working for one column. Question is how to add other two columns?

$files = $_SESSION['itemid'];

$valid_files = array();
if(is_array($files)) {
foreach($files as $file) {

$sql = "SELECT * FROM document_upload WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $file);
$result->execute();

$resArray = $result->fetch();

if (file_exists($filePath . $resArray['upload_lesson_plan'])){
$valid_files[] = $resArray;
}
}
}
if(count($valid_files > 0)){
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}

foreach($valid_files as $res){
$zip->addFile($filePath.$res['upload_lesson_plan']);
// columns that I want to add and take files from...
//$zip->addFile($filePath.$res['upload_worksheet']);
//$zip->addFile($filePath.$res['upload_materials']);
}


Those are both columns which I want to take files from

//$zip->addFile($filePath.$res['upload_worksheet']);
//$zip->addFile($filePath.$res['upload_materials']);


I have tried something like this but doesn't work.. just showing me blank page and doesn't download anything and no errors.

if (file_exists($filePath . $resArray['upload_lesson_plan'] || $filePath . $resArray['upload_worksheet'] || $filePath . $resArray['upload_materials']))


They are stored in columns and they are multiple files in same column comma separated.

Answer

Acording to what you said

They are stored in columns and they are multiple files in same column comma separated.

You can try this way. With explode them:

   foreach($resArray as $col){
   $items = explode(',', $col);

   foreach ($items as $item) {
       if (file_exists($filePath . trim($item))){
            $valid_files[] = $filePath . trim($item);
       }       
   } 

And then call them like this

foreach($valid_files as $res){
  $zip->addFile($res);
}