0

I'm trying to upload and fetch images from database using path. Upload process working perfectly. But, I cannot able to fetch image from db. I've tried print_r($row['image']);. I'm getting the path like this C:/xampp/htdocs/xampp/htdocs/www/images/0d13808ad672c2713d306efbb0e42918. I don't know why this code doesn't fetch image from db?

fetch.php

        <?php
            include('config.php');
            ini_set('display_startup_errors',1); a
            ini_set('display_errors',1);
            error_reporting(-1);

            try
            {
                  $stmt = $conn->prepare("SELECT * FROM imgdb WHERE id = 3");
                  $conn->errorInfo();
                  // $stmt->bindParam('1', $imgid, PDO::PARAM_INT);
                  $stmt->execute();

                  // $path = "/xampp/htdocs/www/images/";
                  // $imgpath = $_SERVER['DOCUMENT_ROOT'].$path;
                   while($row = $stmt->fetch(PDO::FETCH_ASSOC))
                    {
                        echo "<img src=".$row['image']." height='100' width='100'/>"; 
                        print_r($row['image']);
                    }
            } 
            catch (PDOException $e) 
            {
                 echo 'Database Error'.$e->getMessage();
            }
        ?>

upload.php

<?php

    ini_set('display_startup_errors',1);
    ini_set('display_errors',1);
    error_reporting(-1);

      include('config.php');

      if ($_FILES["file"]["error"] > 0)
      {
          echo "Error: " . $_FILES["file"]["error"] . "<br>";
      }
      else
      {
//          echo "Upload: " . $_FILES["file"]["name"] . "<br>";
//          echo "Type: " . $_FILES["file"]["type"] . "<br>";
//          echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
//          echo "Stored in: " . $_FILES["file"]["tmp_name"];
      }


      $filename  = basename($_FILES['file']['tmp_name']);
      $newname = md5($filename);

      $final_save_dir = '/xampp/htdocs/www/images/'.$newname ;
        if(move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $_FILES['file']['name'])) 
        {
            echo "Uploaded";
        } 
        else 
        {
           echo "File was not uploaded";
        }

      $imgid = $_SERVER['DOCUMENT_ROOT'].$final_save_dir;

      try
      {
          $stmt = $conn->prepare("INSERT INTO imgdb ( image ) VALUES ( ? ) ");
          $stmt->bindParam('1', $imgid, PDO::PARAM_STR);
          $conn->errorInfo();
          $stmt->execute();
      }
      catch (PDOException $e) 
      {
          echo 'Database Error'.$e->getMessage();
      }
?>
Karuppiah RK
  • 3,894
  • 9
  • 40
  • 80

4 Answers4

1

Try this and compare with yours, I don't know if it works because I didn't tested, but it should.

upload.php

include('config.php');

if ($_FILES["file"]["error"] > 0 )
{
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
  else
{
    $filename  = basename($_FILES['file']['tmp_name']);
    $ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

    $new_file_name = md5($filename).'.'.$ext;

    $final_save_dir = $_SERVER['DOCUMENT_ROOT'].DS.'www'.DS.'images'.DS;
    if(move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $new_file_name)) 
    {
        echo "Uploaded";
    } 
    else 
    {
       echo "File was not uploaded";
    }

    try
    {
        $stmt = $conn->prepare("INSERT INTO imgdb ( image ) VALUES ( ? ) ");
        $stmt->bindParam('1', $new_file_name, PDO::PARAM_STR);
        $conn->errorInfo();
        $stmt->execute();
    }
    catch (PDOException $e) 
    {
      echo 'Database Error'.$e->getMessage();
    }
}

fetch.php

<?php
include('config.php');
ini_set('display_startup_errors',1); 
ini_set('display_errors',1);
error_reporting(-1);

try
{
      $stmt = $conn->prepare("SELECT * FROM imgdb WHERE id = 3");
      $conn->errorInfo();
      $stmt->execute();

       while($row = $stmt->fetch(PDO::FETCH_ASSOC))
        {
            echo "<img src='images/".$row['image']."' height='100' width='100'/>"; 
        }
} 
catch (PDOException $e) 
{
     echo 'Database Error'.$e->getMessage();
}
Ricardo Barros
  • 205
  • 1
  • 8
0

When you link the image, you have to link to an HTTP accessible path. Use '/' instead of $_SERVER['DOCUMENT_ROOT'] to have a path relative to the web root of your page or 'http://' . $_SERVER['HTTP_HOST'] . '/' (first one is better as the protocol is not defined so it will work on both http and https connections)

mrgeek
  • 117
  • 1
  • 4
  • 1
    And if you want to store the full path as well, you've got the solution, but you cannot link directly to the full path as – mrgeek Mar 12 '14 at 12:33
0

Two things

  1. move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $_FILES['file']['name']) moves the file from the temp location to $final_save_dir.$_FILES['file']['name'] which is different from the value you are storing in the db which is $_SERVER['DOCUMENT_ROOT'].$final_save_dir. You will need to sync these two variables.

  2. Just like @mrgeek pointed you are trying to retrieve an image using the absolute filesystem path not using a http url. if you are using filesystem path you need to use file:/// prepended to the location. But i'm sure this is going to be hosted somewhere so that will not help. so best bet is to use relative urls so that the browser will be able to access it

anurupr
  • 2,294
  • 2
  • 20
  • 28
  • okay i will do using relative url method. is there any example for that? – Karuppiah RK Mar 12 '14 at 12:58
  • you can probably refer to this http://stackoverflow.com/questions/19077075/php-absolute-relative-paths. But you'll need to do this based on the actual location of your images, how your folder is structured ,etc – anurupr Mar 12 '14 at 13:10
0

Have been trying to retrieve image from my database with this code, but it just displays a blank page. Need help

   $user="root";
   $host="localhost";
   $pass="name";
   $db="name";

   $link=mysql_connect($host,$user,$pass);
   if(!$link)die(mysql_error());
   mysql_select_db($db,$link) or die("could not select database.");

 $query_image = "SELECT * FROM img WHERE id=12";
 // This query will show you all images if you want to see only one image pass  acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
 $result = mysql_query($query_image);
 if(mysql_num_rows($result) > 0)
 {
   while($row = mysql_fetch_array($result))
   {
  echo '<img alt="" src="upload/'.$row["img_base_name"].'">';
   }
 }
 else
 {
  echo 'File name not found in database';
 }
?>