Jordan Vit Jordan Vit - 7 months ago 21
SQL Question

Merged multiple pdfs into one wiht PDFMerger

I have trying to select multiple PDF files from database and merged them into one. In database is stored the path to the pds's. What I do is to store in session ID's of the rows and then make query to database and select pdfs for each ID. I have faced this problem:


It is generated only one PDF the first one from the session array.


This is what I have so far:

require_once("database.php");
include 'PDFMerger.php';

$files = $_SESSION['itemid'];
print_r($files);
if(is_array($files)) {

$fileFolder='uploads/';
$pdf = new PDFMerger;

foreach($files as $file) {

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

$resArray = $result->fetchAll();

foreach ( $resArray as $res )
{
$items = explode(',', $res["files"]);

foreach ($items as $item) {

$pdf->addPDF($fileFolder.$item, 'all')

->merge('browser', 'TEST2.pdf');
}
}

}
}


print_r($files);
show that all files are in array.

print_r($resArray);
show only 1 pdf .. first one from the array.

Answer

Yes, you get only one pdf because you must put merge function outside the foreach because in this way you merge only one result. If you merge them after the foreach you will have all of them. Try like this

foreach($files as $file) {

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

    $resArray = $result->fetchAll();

    foreach ( $resArray as $res )
    {
       $items = explode(',', $res["files"]);

       foreach ($items as $item) {

          $pdf->addPDF($fileFolder.$item, 'all');


       }
    }

}     
$pdf->merge('browser', 'TEST2.pdf');