Solved

Upload, store .jpg in MySQL database, then display on webpage

Posted on 2011-03-17
7
921 Views
Last Modified: 2013-12-13
I am trying to adapt code (which works fine) for uploading a .jpg image file, resizing it, storing it in a MySQL database, then displaying it on a webpage. However, this time there will be no resizing to a thumbnail image, the original image of 614width by 778height will be used.

database table name = schedule
database table field name for .jpg image = standings1, type = mediumblob
.jpg images are 90 to 100KB

1)PHP code for initial page (in subfolder admin) that is a form to accept .jpg image file:
<?php
   $id = $_GET['id'];
   $query="Select league from schedule where id = '$id'";
   $result=mysql_query($query);
   $row=mysql_fetch_array($result,MYSQL_ASSOC);
   $league = $row['league'];

   echo "<h2>Upload $league League Standings 1st Image File</h2>\n";

   echo "<form enctype=\"multipart/form-data\" action=\"addstanding1.php\" method=\"post\">\n";
   echo "<table width=\"100%\" cellpadding=\"1\" border=\"1\">\n";
   echo "<input type=\"hidden\" name=\"id\" value=\"$id\">\n";
   echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"2048000\">\n";
   echo "<tr><td><input type=\"file\" name=\"picture\" size=\"75\"></td></tr>\n";
   echo "</table>\n";
   echo "<input type=\"submit\" name=\"button\" value=\"Upload\">\n";
   echo "</form>\n";
?>

2)addstanding1.php file (in subfolder admin) from above form action=
<?php
   include("../mylibrary/login.php");
   login();
   include("../mylibrary/getImage.php");

   $id = $_POST['id'];

   if (get_magic_quotes_gpc())
   {
      $id = stripslashes($id);
   }
   $id = mysql_real_escape_string($id);
   $standings1 = getPict($_FILES['picture']);
   $standings1 = mysql_real_escape_string($standings1);

      $query = "UPDATE schedule SET standings1='$standings1' WHERE id = '$id'";
      $result=mysql_query($query);

      if ($result)
      {
         header("Location: admin.php?p=editstandings");
      }
      else
      {
         echo "<h2>Sorry, I could not process your form at this time</h2>\n";
      }

?>

3)getImage.php file (in subdirectory folder mylibrary) with getPict function called from above addstanding1.php
<?php
function getPict($Original)
{
   if (!$Original['name'])
   {
      // no image supplied, use default
      $TempName = "../images/noimage.jpg";
      $TempFile = fopen($TempName, "r");
      $standings1 = fread($TempFile, fileSize($TempName));
   } else
   {

      // get image
      $Picture =  file_get_contents($Original['tmp_name']);

      //create image
      $SourceImage = imagecreatefromstring($Picture) or die("Cannot imagecreatefromstring");

      if (!$SourceImage)
      {
         //not a valid image
        echo "Not a valid image\n";
        $TempName = "../images/noimage.jpg";
        $TempFile = fopen($TempName, "r");
        $standings1 = fread($TempFile, fileSize($TempName));
      } else
      {

         //create image
         $newpict = imagecreatetruecolor(614, 778) or die("Cannot imagecreatetruecolor");

         $result = imagecopyresampled($newpict, $SourceImage, 0, 0, 0, 0, 614, 778, 614, 778) or die("Cannot imagecopyresampled");

         // move image to variable
         ob_start();
         imagejpeg($newpict);
         $standings1 = ob_get_contents();
         ob_end_clean();
      }
   }
   return $standings1;
}
?>

4)HTML page display.php (in root folder) with the following line of code for displaying the stored image:

<img src="displaystandings.php?id=$id" width="614" height="778">

5)displaystandings.php (in root folder)

<?php
$id = $_GET['id'];
include("./mylibrary/login.php");
login();
header("Content-type: image/jpeg");
$query = "SELECT standings1 from schedule where id = '$id'";
$result = mysql_query($query);
$row=mysql_fetch_array($result, MYSQL_ASSOC);
$img = $row['standings1'];
echo $img;
?>

The result is a page (display.php) that displays a blank image placeholder 614 x 778 instead of the .jpg uploaded and stored in the database. In MyphpAdmin there appears to be images of the correct size in the field standings1.
I can't figure out what is wrong? Please help. Thank You.
0
Comment
Question by:Lasados
  • 4
  • 2
7 Comments
 
LVL 4

Expert Comment

by:te-edu
ID: 35161189
Well first check if file is uploaded. If it is.

echo $_FILES['picture'];

Open in new window


After that add echo in addstanding1.php this code.

 echo $standings1 = getPict($_FILES['picture']);

Open in new window


To see what you get from getPict function. If you have no data check getImage.php .



0
 

Author Comment

by:Lasados
ID: 35161356
Thanks for your reply and suggestions.
I don't really understand the first suggestion; when I deleted the database update lines from addstandings1.php and replaced them like this:
<?php
   include("../mylibrary/login.php");
   login();
   include("../mylibrary/getImage.php");

   $id = $_POST['id'];

   if (get_magic_quotes_gpc())
   {
      $id = stripslashes($id);
   }
   $id = mysql_real_escape_string($id);
   echo $_FILES['picture'];
?>

then the output was the word "Array". However when I relaced the last line with your 2nd suggestion as here:
<?php
   include("../mylibrary/login.php");
   login();
   include("../mylibrary/getImage.php");

   $id = $_POST['id'];

   if (get_magic_quotes_gpc())
   {
      $id = stripslashes($id);
   }
   $id = mysql_real_escape_string($id);
   echo $standings1 = getPict($_FILES['picture']);
?>

then the output was the image file displayed correctly! Hence I believe the file is uploaded correctly with: $standings1 = getPict($_FILES['picture']);
Thus getImage.php and it's function getPict() should be working correctly.
So what can I do next?
1) How to test if subsequent insertion into database is correct.
2) If subsequent insertion into database is correct, how to debug display problems of the stored image?
0
 
LVL 4

Expert Comment

by:te-edu
ID: 35162906
echo $_FILES['picture']; - you get array OK

use print_r( $_FILES['picture']); - instead to see key that holds image data.

if you get eg. Array([0]=>image data )

 then replace
[b]
 $standings1 = mysql_real_escape_string($standings1[NUMBER THAT HOLDS IMAGE DATA]);[/b]

Open in new window


1. Output Mysql query

echo $query = "UPDATE schedule SET standings1='$standings1' WHERE id = '$id'";

Open in new window


This part standings1='$standings1' - copy/paste into text file and changge extension to .jpg, jpeg open file and see if you see image. IF ok check database and check database encoding
Output show image query:

$query = "SELECT standings1 from schedule where id = '$id'";

Open in new window


and echo $img; replace with print_r($img); it could be  $img[0] you need to output.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 14

Accepted Solution

by:
Scott Madeira earned 500 total points
ID: 35164756
Not to totally rewrite your application but wouldn't it be more efficient to upload the image file to a directory on the server with a unique name and store a link to that file name in the database?  I'm not a huge fan of putting images into a database.

addstanding1.php becomes simpler because you just convert the picture and then do the redirect.  No need to update the database since you aren't putting the image in the database.

If you name the images with a standard convention: imagefile012345.jpg for example then this in step 3 eliminates the need for the output buffering to create the file.  You just save it as a jpg file in imagejpeg($newpict, $filename) and return either success or failure since you already know the filename based on the ID that was passed in.

In step 4 this:

<img src="displaystandings.php?id=$id" width="614" height="778">

becomes something like this (and eliminates a call to the database):

<img src="<?php echo '/path/to/images/image'.$id.'.jpg' ?>" width="614" height="778">  which would resolve to:

<img src="/path/to/images/image012345.jpg" width="614" height="778">

You would want to do a check to see if the file exists.  If not, post a blank or a default image...

I think what you are trying to accomplish could be done a lot easier than the code you are adapting from.

0
 

Author Comment

by:Lasados
ID: 35164879
Thanks smadeira. I found a post which utilizes your approach here:
http://www.experts-exchange.com/Web_Development/Images/Q_24016457.html

I will give this a try since the latest prior suggestion didn't work; I still get a blank image.
0
 

Author Closing Comment

by:Lasados
ID: 35168572
Thanks smadeira!
0
 

Author Comment

by:Lasados
ID: 35168659
Using the following code I adapted from the prior post and smadeira's solution I was able to solve the problem without storing the image or path to the image in the database at all. I simply upload the .jpg file, name it a unique name of image + $id + .jpg, move to a specified folder, then use my display.php page to display the image based on id as smadeira suggested. It works great!

addstanding1.php

<?php
    // image directory
    $uploadDir = ( $_SERVER['DOCUMENT_ROOT'].'/imgupload/' );
 
    $id = $_POST['id'];
    $tmpName  = $_FILES['picture']['tmp_name'];
         
    // generate the file name
    $setName = "image" . $id . '.jpg';
         
    // file path for the upload file
    $filePath = $uploadDir . $setName;
 
    // move the files to the specified directory with error reporting
    $result = move_uploaded_file($tmpName, $filePath);
    if (!$result)
       {
         header("Location: admin.php?p=error");
       }
    else
      {
         header("Location: admin.php?p=editstandings");
      }
?>
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now