Display an image from a database PHP/MySQL


Displaying an image from a database is easy to do using PHP. For this code snippet it will retrieve the image and display it using an html tag.

Get the image:

<?php

  $id = $_GET['id'];
  // do some validation here to ensure id is safe

  $link = mysql_connect("localhost", "root", "");
  mysql_select_db("dvddb");
  $sql = "SELECT dvdimage FROM dvd WHERE id=$id";
  $result = mysql_query("$sql");
  $row = mysql_fetch_assoc($result);
  mysql_close($link);

  header("Content-type: image/jpeg");
  echo $row['dvdimage'];
?>

Display image:

<!-- displaying the image using the body html tag -->
<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>
Advertisements

One thought on “Display an image from a database PHP/MySQL

  1. This is very, very insecure. Injecting user input into directly into an SQL statement without any validation or cleaning is a recipe for disaster.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s