Tuesday, July 5, 2022
HomePHPHow to upload multiple images in PHP and store in database

How to upload multiple images in PHP and store in database

In this article, you going to see how to upload multiple images in PHP and store in database with example in a step by step.

If you looking for this topic then you are at a right place.

Before going to start with the topic, make sure that you have a database with a table name Image.

So to create a table with name image in the database, execute to the below query.

-- Table structure for table `images`
CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `image` varchar(255) NOT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Let’s start with the topic of upload multiple images in PHP.

To add multiple images, declare a button or anchor with id.

This ID is get called with help of on click event listener using jQuery.

In the next, as button get click every time form get called which consist of file upload input.

So using this every time on click browse upload button name as choose file get display.

Then next step is to click every time browse button to upload image.

As all image is get set to upload, finally at end click submit button to upload multiple images.

Upload Multiple Image in PHP
Upload Multiple Image in PHP

To upload multiple image make sure regarding the configuration section for the database connection.

With the help of the database connection, multiple images is get uploaded in the folder and in the database.

Below to code snippet for the database connection.

<?php 
   /* database configuaration */
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', 'root');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'phpimagetutorial');
   $con  = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

   // Check connection
	if (mysqli_connect_errno()) {
	  echo "Failed to connect to MySQL: " . mysqli_connect_errno();
	  exit();
	}
?>

Above code snippet add to root folder and save in a file called as cofig.php file.

After including config file in top section there is not necessary pass the detail for database connection again and again.

The layout of Multiple images uploads code snippet given below.

<?php 
    if(isset($successMsg) && !empty($successMsg))
    {
        echo "<div class='success-msg'>";
        foreach($successMsg as $smsg)
        {
            echo $smsg."<br>";
        }
        echo "</div>";
    }
?>
<?php 
    if(isset($errorMsg) && !empty($errorMsg))
    {
        echo "<div class='error-msg'>";
        foreach($errorMsg as $emsg)
        {
            echo $emsg."<br>";
        }

        echo "</div>";
    }
?>
<div class="add-more-cont"><a id="multipleImg"><img width="100px" src="img/addimage.png">To Add Multiple Image - Please click Add Icon Image</a></div>
<form name="uploadFile" action="" method="post" enctype="multipart/form-data" id="upload-form">
    <div class="input-files">
    <input type="file" name="image_upload-1">
    </div>
    <input type="submit" name="submit" value="submit">
</form>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        var id = 1;
        $("#multipleImg").click(function(){
            var showId = ++id;
            if(showId <=10)
            {
                $(".input-files").append('<input type="file" name="image_upload-'+showId+'">');
            }
        });
    });
</script>

Multiple images upload code snippet is give below from which you can understand how move_uploaded_file function is used to move all the images to folder.

The image is get move to folder and then insert query is get executed to insert the images into the database.

Below is code snippet for upload multiple images.

<?php 
	include("config.php");
	if(isset($_POST['submit']))
	{
		$targetFolder = "imageuploads";
		$errorMsg = array();
		$successMsg = array();
		foreach($_FILES as $file => $fileArray)
		{
			if(!empty($fileArray['name']) && $fileArray['error'] == 0)
			{
				$getFileExtension = pathinfo($fileArray['name'], PATHINFO_EXTENSION);;

				if(($getFileExtension =='jpg') || ($getFileExtension =='jpeg') || ($getFileExtension =='png') || ($getFileExtension =='gif'))
				{
					if ($fileArray["size"] <= 500000) 
					{
						$breakImgName = explode(".",$fileArray['name']);
						$imageOldNameWithOutExt = $breakImgName[0];
						$imageOldExt = $breakImgName[1];

						$newFileName = strtotime("now")."-".str_replace(" ","-",strtolower($imageOldNameWithOutExt)).".".$imageOldExt;

						
						$targetPath = $targetFolder."/".$newFileName;

						
						if (move_uploaded_file($fileArray["tmp_name"], $targetPath)) 
						{
							
							$qry ="insert into images (image) values ('".$newFileName."')";


							$rs  = mysqli_query($con, $qry);

							if($rs)
							{
								$successMsg[$file] = "Image is uploaded successfully";
							}
							else
							{
								$errorMsg[$file] = "Unable to save ".$file." file ";
							}
						}
						else
						{
							$errorMsg[$file] = "Unable to save ".$file." file ";		
						}
					} 
					else
					{
						$errorMsg[$file] = "Image size is too large in ".$file;
					}

				}
				else
				{
					$errorMsg[$file] = 'Only image file required in '.$file.' position';
				}	
			}
			
		}
	}
?>

Delete Image from folder in PHP

Complete code snippet for multiple images upload.

<?php 
	include("config.php");
	if(isset($_POST['submit']))
	{
		$targetFolder = "imageuploads";
		$errorMsg = array();
		$successMsg = array();
		foreach($_FILES as $file => $fileArray)
		{
			if(!empty($fileArray['name']) && $fileArray['error'] == 0)
			{
				$getFileExtension = pathinfo($fileArray['name'], PATHINFO_EXTENSION);;

				if(($getFileExtension =='jpg') || ($getFileExtension =='jpeg') || ($getFileExtension =='png') || ($getFileExtension =='gif'))
				{
					if ($fileArray["size"] <= 500000) 
					{
						$breakImgName = explode(".",$fileArray['name']);
						$imageOldNameWithOutExt = $breakImgName[0];
						$imageOldExt = $breakImgName[1];

						$newFileName = strtotime("now")."-".str_replace(" ","-",strtolower($imageOldNameWithOutExt)).".".$imageOldExt;

						
						$targetPath = $targetFolder."/".$newFileName;

						
						if (move_uploaded_file($fileArray["tmp_name"], $targetPath)) 
						{
							
							$qry ="insert into images (image) values ('".$newFileName."')";


							$rs  = mysqli_query($con, $qry);

							if($rs)
							{
								$successMsg[$file] = "Image is uploaded successfully";
							}
							else
							{
								$errorMsg[$file] = "Unable to save ".$file." file ";
							}
						}
						else
						{
							$errorMsg[$file] = "Unable to save ".$file." file ";		
						}
					} 
					else
					{
						$errorMsg[$file] = "Image size is too large in ".$file;
					}

				}
				else
				{
					$errorMsg[$file] = 'Only image file required in '.$file.' position';
				}	
			}
			
		}
	}
?>
<!DOCTYPE html>
<html>
<head>
<title>how to upload multiple images in php and store in mysql database</title>
<link rel="stylesheet" href="style.css" type='text/css'>
</head>
<body>
	<div class="form-container">

	<?php 
		if(isset($successMsg) && !empty($successMsg))
		{
			echo "<div class='success-msg'>";
			foreach($successMsg as $smsg)
			{
				echo $smsg."<br>";
			}
			echo "</div>";
		}
	?>
	<?php 
		if(isset($errorMsg) && !empty($errorMsg))
		{
			echo "<div class='error-msg'>";
			foreach($errorMsg as $emsg)
			{
				echo $emsg."<br>";
			}

			echo "</div>";
		}
	?>
	<div class="add-more-cont"><a id="multipleImg"><img width="100px" src="img/addimage.png">To Add Multiple Image - Please click Add Icon Image</a></div>
	<form name="uploadFile" action="" method="post" enctype="multipart/form-data" id="upload-form">
		<div class="input-files">
		<input type="file" name="image_upload-1">
		</div>
		<input type="submit" name="submit" value="submit">
	</form>
	
	</div>
	
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
	<script>
		$(document).ready(function(){
			var id = 1;
			$("#multipleImg").click(function(){
				var showId = ++id;
				if(showId <=10)
				{
					$(".input-files").append('<input type="file" name="image_upload-'+showId+'">');
				}
			});
		});
	</script>
</body>
</html>

Conclusion:

Finally, we have done with how to upload multiple images in PHP and store in database.

I hope you like this article and if you feel like we missed out on anything, please comment below.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular