Multiple IMAGE Add and Store in Folder Using PHP and MySQL

How to Multiple IMAGE Add and Store in Folder Using PHP and MySQL?

Spread the love

We will learn how to select all the images from PHP at once and store them in a database and move that file to a Folder.

Document transfer in PHP is the most utilized usefulness for web applications. A solitary document or various records can be effectively transferred utilizing PHP. PHP gives a fast and straightforward approach to carry out worker-side document transfer usefulness. For the most part, in the web application, the document is transferred to the worker and the record name is put away in the information base. Later the documents are recovered from the worker dependent on the record name put away in the information base.

Much of the time, a solitary picture is transferred on the double. Be that as it may, some of the time you have a necessity to transfer various pictures immediately. In this instructional exercise, we will tell you the best way to transfer various pictures in PHP and store the pictures in the MySQL data set. Various picture transfer permits the client to choose numerous records immediately and transfer all documents to the worker in a solitary snap.

Our model code will execute the accompanying usefulness to show the various pictures transfer in PHP.HTML structure to choose different pictures. Transfer pictures to the worker utilizing PHP. Store document names in the information base utilizing PHP and MySQL. Recover pictures from the information base and show them on the page.

First, we will create a database then we will create a table in it. Now fill in the details of ID, file_name, uploaded_on, and status table. Now we will create a dbConfig.php file in your sublime coeditor and another file index.php. Now you can see how many steps I have, how to add files, and how to store all images in a database using PHP.

Note:- Database name is multipleimages.

Step1:- Create New Database and Table

CREATE TABLE `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Step2:- Create Database Configuration File [ File name in dbConfig.php ]

<?php
// Database configuration
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName     = "multipleimages";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}
?>

Step3:- Now create a folder named uploads where your index.php file is.

Step4:- Create index.php File and Add CSS and also add PHP Code

<!DOCTYPE html>
<html>
<head>
	<title>Multiple Images Select and store</title>

</head>
<body>

<form action="" method="post" enctype="multipart/form-data">
    Select Image Files to Upload:
    <input type="file" name="files[]" multiple >
    <input type="submit" name="submit" value="UPLOAD">
</form>
</body>
</html>

CSS

<style type="text/css">
    form{
        background: #f3f3f3;
        padding: 50px;
    }
    img{
        width: 150px;
        padding: 20px;
    }
</style>

PHP Code

Copy this code and add it to your index.php File.

<?php 
if(isset($_POST['submit'])){ 
    // Include the database configuration file 
    include_once 'dbConfig.php'; 
     
    // File upload configuration 
    $targetDir = "uploads/"; 
    $allowTypes = array('jpg','png','jpeg','gif'); 
     
    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; 
    $fileNames = array_filter($_FILES['files']['name']); 
    if(!empty($fileNames)){ 
        foreach($_FILES['files']['name'] as $key=>$val){ 
            // File upload path 
            $fileName = basename($_FILES['files']['name'][$key]); 
            $targetFilePath = $targetDir . $fileName; 
             
            // Check whether file type is valid 
            $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); 
            if(in_array($fileType, $allowTypes)){ 
                // Upload file to server 
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){ 
                    // Image db insert sql 
                    $insertValuesSQL .= "('".$fileName."', NOW()),"; 
                }else{ 
                    $errorUpload .= $_FILES['files']['name'][$key].' | '; 
                } 
            }else{ 
                $errorUploadType .= $_FILES['files']['name'][$key].' | '; 
            } 
        } 
         
        if(!empty($insertValuesSQL)){ 
            $insertValuesSQL = trim($insertValuesSQL, ','); 
            // Insert image file name into database 
            $insert = $db->query("INSERT INTO images (file_name, uploaded_on) VALUES $insertValuesSQL"); 
            if($insert){ 
                $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):''; 
                $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):''; 
                $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType; 
                $statusMsg = "Files are uploaded successfully.".$errorMsg; 
            }else{ 
                $statusMsg = "Sorry, there was an error uploading your file."; 
            } 
        } 
    }else{ 
        $statusMsg = 'Please select a file to upload.'; 
    } 
     
    // Display status message 
    echo $statusMsg; 
} 
?>

Also Copy this code and add it to your index.php File.

<?php
// Include the database configuration file
include_once 'dbConfig.php';

// Get images from the database
$query = $db->query("SELECT * FROM images ORDER BY id DESC");

if($query->num_rows > 0){
    while($row = $query->fetch_assoc()){
        $imageURL = 'uploads/'.$row["file_name"];
?>
    <img src="<?php echo $imageURL; ?>" alt="" />
<?php }
}else{ ?>
    <p>No image(s) found...</p>
<?php } ?> 

Output:-

How to select Multiple images simultaneously using PHP and store them in a Database


Spread the love

Related Posts

One thought on “How to Multiple IMAGE Add and Store in Folder Using PHP and MySQL?

Leave a Reply

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