Jordan Vit Jordan Vit - 7 months ago 42
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

require_once("database.php");

if(isset($_GET['upload_id']) && is_numeric($_GET['upload_id']))
{
$fileFolder='uploads/';

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

$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));
@read($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
RELOAD

Answer

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']);
$result->execute();     
$resArray = $result->fetch(PDO::FETCH_ASSOC);
$file = $resArray['file'];// get your file name

By using fetchAll

Pass PDO::FETCH_COLUMN, 0

 $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
 $file = $resArray[0];// get your file name