Jordan Vit Jordan Vit - 2 years ago 105
SQL Question

Opening pdf with mysql and php

I'm storing pdf's on the filesystem and path in database table. I want now based on the ID to open corresponded PDF document in the browser. How can I open and read PDF's?
What I have so far is this


if(isset($_GET['upload_id']) && is_numeric($_GET['upload_id']))

$sql = "SELECT file FROM documents WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);

$resArray = $result->fetchAll();

$file = $resArray['file'];

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($fileFolder.$file));


When I click on the button and tried to open the pdf I got this message in the Chrome

Failed to load PDF document

Answer Source

You can get your file name using fetch(PDO::FETCH_ASSOC); which Return next row as an array indexed by column name

$sql = "SELECT file FROM documents WHERE upload_id = :id"; 
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);
$resArray = $result->fetch(PDO::FETCH_ASSOC);
$file = $resArray['file'];// get your file name

By using fetchAll


 $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
 $file = $resArray[0];// get your file name
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download