How to Upload Image to Database and Server using HTML,PHP and MySQL

In this tutorial I’m going to teach you how you can Upload Image to Database and Server using HTML, PHP and MySQL. Image Uploading is very easy there are two ways you can upload the image either to the database or to the server as you like. You may also like Multiple file upload in Codeigniter and Multiple Image Upload in PHP.

Example 1

<?php
    define('DB_SERVER', "localhost");
    define('DB_USER', "root");
    define('DB_PASS', "");
    define('DB_DATABASE', "whatsappdwld_db");
    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
    if(isset($_POST['submit_image']))
    {
        $imagename=$_FILES["myimage"]["name"]; 
        $imagetmp=addslashes (file_get_contents($_FILES['myimage']['tmp_name']));
        $insert_image="INSERT INTO image_table (imagecontent,imagename) VALUES('$imagetmp','$imagename')";
        mysqli_query($con,$insert_image);
        
        header("content-type:image/jpeg");
        
        $select_image="select * from image_table where imagename='$imagename'";
        $var = mysqli_query($con,$select_image);
        if($row = mysql_fetch_assoc($var))
        {
            echo $image_name = $row["imagename"];
            echo $image_content = $row["imagecontent"];
        }
        
    }
?>

<html>
    <body>
        <form method="POST" action="" enctype="multipart/form-data">
            <input type="file" name="myimage">
            <input type="submit" name="submit_image" value="Upload">
        </form>
    </body>
</html>

Example 2

<?php
    define('DB_SERVER', "localhost");
    define('DB_USER', "root");
    define('DB_PASS', "");
    define('DB_DATABASE', "whatsappdwld_db");
    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
    if(isset($_POST['submit_image']))
    {
        $upload_image=$_FILES[" myimage "][ "name" ];
        $folder="images/";
        move_uploaded_file($_FILES[" myimage "][" tmp_name "],$folder.$_FILES[" myimage "][" name "]);
        $insert_path = "INSERT INTO image_table (path,imagename) VALUES('$folder','$upload_image')";
        mysqli_query($con,$inser_path);
        echo "Success";
    }
?>

<html>
    <body>
        <form method="POST" action="" enctype="multipart/form-data">
            <input type="file" name="myimage">
            <input type="submit" name="submit_image" value="Upload">
        </form>
    </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *