[php] How to upload images into MySQL database using PHP code

I am trying to save images in my database from HTML form. I have written PHP code to accomplish this task. The program is not generating any error message, but also not inserting image data in MySQL database. Kindly check it. Here i am sharing a excerpt from my code.

        /*-------------------
    IMAGE QUERY 
    ---------------*/


    $file   =$_FILES['image']['tmp_name'];
    if(!isset($file))
    {
      echo 'Please select an Image';
    }
    else 
    {
       $image_check = getimagesize($_FILES['image']['tmp_name']);
       if($image_check==false)
       {
        echo 'Not a Valid Image';
       }
       else
       {
        $image = file_get_contents ($_FILES['image']['tmp_name']);
        $image_name = $_FILES['image']['name'];
        if ($image_query = mysql_query ("insert into product_images values (1,'$image_name',$image )"))
        {
          echo $current_id;
         //echo 'Successfull';
        }
        else
        {
          echo mysql_error();
        }
       }
   }
        /*-----------------
    IMAGE QUERY END
    ---------------------*/

    <form action='insert_product.php' method='POST' enctype='multipart/form-data' ></br>
            File        : <input type='file' name= 'image' >
    </form>

Error Message You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

This question is related to php html mysql database image-uploading

The answer is


This is the perfect code for uploading and displaying image through MySQL database.

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
    if(isset($_POST['submit']))
    {
     if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
     {
        echo " error ";
     }
     else
     {
        $image = $_FILES['image']['tmp_name'];
        $image = addslashes(file_get_contents($image));
        saveimage($image);
     }
    }
    function saveimage($image)
    {
        $dbcon=mysqli_connect('localhost','root','','dbname');
        $qry="insert into tablename (name) values ('$image')";
        $result=mysqli_query($dbcon,$qry);
        if($result)
        {
            echo " <br/>Image uploaded.";
            header('location:urlofpage.php');
        }
        else
        {
            echo " error ";
        }
    }
?>
</body>
</html>

Just few more details:

  • Add mysql field

`image` blob

  • Get data from image

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));

  • Insert image data into db

$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";

  • Show image to the web

<img src="data:image/png;base64,'.base64_encode($row['image']).'">

  • End

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str

Examples related to image-uploading

How to store images in mysql database using php Multiple Image Upload PHP form with one input Uploading Images to Server android How to upload images into MySQL database using PHP code Check file size before upload ios Upload Image and Text using HTTP POST Send file via cURL from form POST in PHP What is the best place for storing uploaded images, SQL database or disk file system?