Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a problem in retrieving an image from a database. Here is the code that uploads the image to the database:

<form method="post" action="index2.php" enctype="multipart/form-data">
  <input type="file" name="drimg2"/>
  <input  type="submit" name="submit2" value="Save"/>
</form>

<?php

if(isset($_POST['submit2'])) {

  $con=mysql_connect("localhost","root","root");
  mysql_select_db("test",$con);

  $imgname1=$_FILES['drimg2']['name'];
  echo $imgname1;

  $imageextension1 = substr(strrchr($imgname1,'.'), 1);
  if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
    die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
  }

  if (($imageextension1= "jpg") && ($imageextension1= "jpeg") && ($imageextension1= "gif") && ($imageextension1 = "png") && ($imageextension1 = "bmp")) {   
    $query1=mysql_query("INSERT INTO store set image='$imgname1'");
    $action = move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1); 
    die('not Uploded');
  }
}
?> 

Now I want to retrieve all the images in the database; for this I am using the following code:

<?php
$query1="select * from store";
$fetch=mysql_query($query1);

while ($rows=mysql_fetch_array($fetch)) {
  echo "<img  src='images/".$rows['image']."'  />";   
}
?> 
share|improve this question
 
tbh you cant upload a image with just "; } ?> –  EaterOfCorpses Aug 8 '12 at 7:49

2 Answers

Refer this link,

Hope this will help. Change retrieval of image code to following,

$content = $row['image'];

header('Content-type: image/jpg');
     echo $content;
share|improve this answer
1  
Try to post an example just in case the site goes offline. –  JLevett Aug 8 '12 at 7:57
 
$query = "SELECT * FROM store WHERE id =30"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { echo $img=$row['name']; echo "<img src='".$row['name']."'/>" } I am using this code to display the image using path of it. –  Wajahat Ahmed Aug 11 '12 at 7:59
 
@WajahatAhmed What do you want to do? Do you want to retrieve your stored image from database server? or from file server? In your que it seems you want it from database and now you are taking it from file server. Be specific so i can help you. –  Vinay Aug 13 '12 at 5:08

You should not be using the old mysql_* functions and use PDO or mysqli instead. Here is a much cleaner and securer way of doing what you want.

<?php 
/**
 * A Simple class to handle your database requests
 * related to your image storage ect
 */
class image_model{
    private $db;
    function __construct($db){
        $this->db = $db;
    }

    function add($img_name){
        $sql = "INSERT INTO store (image) VALUES (:value)";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':value', $img_name, PDO::PARAM_STR);
        $stmt->execute();
    }

    function get_all(){
        $sql = "SELECT image FROM store";
        return $this->db->query($sql)->fetchAll();
    }
    //Perhaps use in future
    function get_image($id){
        $sql = "SELECT image FROM store WHERE id=:id";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
        return $result->fetchAll();
    }
}

//Connect safely to your database...
try{
    $db = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
    die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}

//Create an instance of the image model above
$img_model = new image_model($db);

//Boom...Handle the upload
if($_SERVER['REQUEST_METHOD']=='POST'){
    if ($_FILES["img"]["error"] > 0){
        echo "Error: ".$_FILES["img"]["error"]."<br />";
    }else{
        $img = getimagesize($_FILES["img"]["tmp_name"]);

        $allowed = array('image/jpeg','image/gif','image/png','image/bmp');
        //Width and height must be more then 0 pixles and mime must be in allowed array
        if($img[0] > 0 && $img[1] > 0 && in_array($img['mime'],$allowed)){
            if(is_uploaded_file($_FILES["img"]["tmp_name"])){
                //Clean image name
                $img_name = preg_replace('/[^a-zA-Z0-9.-]/s', '_', basename($_FILES["img"]["name"]));
                //move image to folder
                move_uploaded_file($_FILES["img"]["tmp_name"],"images/".$img_name);
                //Add image to db using a method from the image model
                $img_model->add($img_name);
            }
        }else{
            echo "Error: Unknown extension. Only jpg, bmp and gif files are allowed. Please hit the back button on your browser and try again.<br />";
        }

    }
}

//Your form
?>
<h1>Upload image</h1>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="img"/>
<input  type="submit" name="submit" value="Save"/>
</form>

<?php 
//Access your image model in a simple way and get all images
foreach($img_model->get_all() as $row){
  echo '<img src="images/'.$row['image'].'" /><br />';  
}
?>
share|improve this answer
 
it's not showing anything on th page –  Wajahat Ahmed Aug 8 '12 at 10:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.