jackkds7
jackkds7

Reputation: 152

Insert and retrieve Image from Mysql database

I'm new to php. I want to add images into Database and display every image when new image is uploaded. Every image is getting inserted into database. My problem is only first image is getting retrieved but i want to display all images from database.This is my code

<?php
    ini_set('mysql.connect_timeout', 300);
    ini_set('default_socket_time',300);

?>


<html>
<body>
    <form method="POST" enctype="multipart/form-data">
    <br>
        <input type="file" name="image">
        <br><br>    
        <input type="submit" name="submit" value="upload">

    </form>
    <?php
        if(isset($_POST['submit']))
        {
            if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
            {
                echo "Please select an image.";
            }
            else{
                $image=addslashes($_FILES['image']['tmp_name']);
                $name=addslashes($_FILES['image']['name']);
                $image=file_get_contents($image);
                $image=base64_encode($image);
                saveimage($name,$image);
            }
        }
        displayimage();
        function saveimage($name,$image)
        {
            $con=mysql_connect("localhost","root","");
            mysql_select_db("sanket",$con);
            $qry="insert into images (name,image) value ('$name','$image')";
            $result=mysql_query($qry,$con);
            if($result)
            {
                //echo "<br>Image uploaded.";
            }
            else
            {
                //echo "<br>Image not uploaded";
            }
        }
        function displayimage()
        {
            $con=mysql_connect("localhost","root","");
            mysql_select_db("sanket",$con);
            $qry="select * from images";
            $result=mysql_query($qry,$con);
            while($row = mysql_fetch_array($result))
            {
                echo '<img height="300" width="300" src="data:image;base64,'.$row['image'].'"'; 
            }
            mysql_close($con);
        }
    ?>
</body>

</html>

Upvotes: 1

Views: 109

Answers (1)

Arun Krish
Arun Krish

Reputation: 2153

You didnt close the image tag. use it like this

echo '<img height="300" width="300" src="data:image;base64,'.$row['image'].'" />'; 

Upvotes: 2

Related Questions