download image from mysql using php

Solutions on MaxInterview for download image from mysql using php by the best coders in the world

showing results for - "download image from mysql using php"
David
14 Mar 2020
1//You can save this to test.php and call it with test.php?id=1 for example
2<?php
3
4//Database class with PDO (MySQL/MariaDB)
5require_once("database.php"); //If you need this, write to office@predl.cc i'll send you the db class
6
7//Connect to database
8$database = new Database();
9$pdo = $database->dbConnection();
10
11//Get ID from GET (better POST but for easy debug...)
12if (isset($_GET["id"])) {
13	$id=(int)$_GET["id"];
14} else {
15  echo "Wrong input";
16  exit;
17}
18
19//Prepare PDO SQL
20$q = $pdo->prepare("SELECT * FROM `table_with_image` WHERE `id`=:p_id");
21
22//Add some data
23$q->bindparam(":p_id", $id); //Filter user input, no sanitize necessary here
24
25//Do the db query
26$q->execute();
27
28//If something found (always only 1 record!)
29if ($q->rowCount() == 1) {
30  
31  	//Get the content of the record into $row
32	$row = $q->fetch(PDO::FETCH_ASSOC); //Everything with id=$id should be in record buffer
33  	
34  	//This is the image blob mysql item  
35  	$image = $row['image'];
36  	
37  	//Clean disconnect
38  	$database->disconnect();
39    
40  	//Now start the header, caution: do not output any other header or other data!
41  	header("Content-type: image/jpeg");
42    header('Content-Disposition: attachment; filename="table_with_image_image'.$id.'.jpg"');
43    header("Content-Transfer-Encoding: binary"); 
44    header('Expires: 0');
45    header('Pragma: no-cache');
46    header("Content-Length: ".strlen($image));
47    //Output plain image from db
48	echo $image;
49} else {
50  //Nothing found with that id, output some error
51  $database->disconnect();
52  echo "No image found";
53}
54
55//No output and exceution further this point
56exit();