image does not fetch from database using path

走远了吗. 提交于 2019-12-13 04:40:00

问题


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();
      }
?>

回答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();
}



回答2:


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)




回答3:


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




回答4:


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';
 }
?>


来源:https://stackoverflow.com/questions/22351530/image-does-not-fetch-from-database-using-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!