how to insert image in database using php? – 2 ways to insert images in mysql Example

how to insert image in database using php : In some registration or sign up HTML For via php as well as web application i required image upload. For Example: For User Profile picture upload, Your Product gallery photo upload, portfolio image etc.

how to insert image in database using php?

There are Main 2 methods to insert images in mysql database.

  • binary format insert
  • image upload in folder
  • how to insert image in database using php
    how to insert image in database using php

    Using binary format

    In this type I directly simple step by step insert the image in mysql database table using binary format.

    Using all the any types of the image upload in single folder

    In this type i upload the image in a folder as well as store the image name in MySql database table.

    Read Also:  10 digit mobile number validation in javascript

    For insert query to image in MySQL first i have to create a table in data base.

    CREATE TABLE `portfolio` (
    `id` int(11) NOT NULL,
    `portfolio_img` varchar(55) NOT NULL
      ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    index.php

    <!DOCTYPE html>
    <html>
    <head>
        <title>Insert Image in MySql using PHP - www.pakainfo.com</title>
    </head>
    <body>
    
    <form action="do_upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="portfolio_img[]" />
        <button type="submit">Upload</button>
    </form>
    </body>
    </html>
    

    do_upload.php

    <?php
    $cn=mysqli_connect("localhost","root","","portfolio_img") or die("Could not Connect My Sql");
    $folder_path = "media/";/* Path for file upload */
    	$uniq_key   = time();
    	$project_img_name      = str_replace(' ','-',strtolower($_FILES['portfolio_img']['name'][0]));
    	$ImageType      = $_FILES['portfolio_img']['type'][0];
     
    	$getImgExt = substr($project_img_name, strrpos($project_img_name, '.'));
    	$getImgExt       = str_replace('.','',$getImgExt);
    	$project_img_name      = preg_replace("/\.[^.\s]{3,4}$/", "", $project_img_name);
    	$uniq_imgnm = $project_img_name.'-'.$uniq_key.'.'.$getImgExt;
        $ret[$uniq_imgnm]= $folder_path.$uniq_imgnm;
    	
    	/* Try to make the folder path if it does not exist */
    	if (!file_exists($folder_path))
    	{
    		@mkdir($folder_path, 0777);
    	}               
    	move_uploaded_file($_FILES["portfolio_img"]["tmp_name"][0],$folder_path."/".$uniq_imgnm );
    	     $sql = "INSERT INTO `portfolio_img`(`portfolio_img`)VALUES ('$uniq_imgnm')";
    		if (mysqli_query($cn, $sql)) {
    			echo "successfully !";
    		}
    		else {
    		echo "Error: " . $sql . "" . mysqli_error($cn);
    	 }
    
    ?>
    

    Don’t Miss : How To Upload File/Image In CodeIgniter?

    CREATE TABLE `portfolio_img` (
    `id` int(11) NOT NULL,
    `portfolio_img` LONGBLOB NOT NULL
      ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
      
    

    Here we using 1 file for insert portfolio_img in MySQL:

    Read Also:  Javascript Forms Required Fields validation Example

    Simple HTML form that allow users to select the portfolio_img file they want to upload.

    Using binary format

    index.php

    <!DOCTYPE html>
    <html>
    <head>
        <title>Insert Image in MySql using PHP - www.pakainfo.com</title>
    </head>
    <body>
    <?php
    $msg = '';
    if($_SERVER['REQUEST_METHOD']=='POST'){
        $portfolio_img = $_FILES['portfolio_img']['tmp_name'];
        $img = file_get_contents($portfolio_img);
        $link = mysqli_connect('localhost','root','','tamil_v1') or die('sorry, Unable To connect');
        $sql = "insert into portfolio imgs (portfolio_img) values(?)";
    
        $stmt = mysqli_prepare($link,$sql);
    
        mysqli_stmt_bind_param($stmt, "s",$img);
        mysqli_stmt_execute($stmt);
    
        $check = mysqli_stmt_affected_rows($stmt);
        if($check==1){
            $msg = 'Good Luck, Image Successfullly UPloaded';
        }else{
            $msg = 'sorry, Error uploading portfolio_img';
        }
        mysqli_close($link);
    }
    ?>
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="portfolio_img" />
        <button>Upload</button>
    </form>
    <?php
        echo $msg;
    ?>
    </body>
    </html>
    


    I hope you get an idea about how to insert image in database using php.
    I would like to have feedback on my infinityknow.com blog.
    Your valuable feedback, question, or comments about this article are always welcome.
    If you enjoyed and liked this post, don’t forget to share.