You can store the image files in the Database table either in base64 format or its path after uploading.
In the base64 method, it is not necessary to store the uploaded file on the server because it is been directly accessed with the base64 encoded value.
In this tutorial, I am using PDO connection for storing multiple image files path in the MySQL database table.
Contents
1. Table structure
I am using images
table for storing data.
CREATE TABLE `images` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(80) NOT NULL, `image` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a config.php
file for the database connection.
Completed Code
<?php $server = "localhost"; $username = "root"; $password = ""; $dbname = "tutorial"; // Create connection try{ $conn = new PDO("mysql:host=$server;dbname=$dbname","$username","$password"); $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); }catch(PDOException $e){ die('Unable to connect with the database'); }
3. HTML
Create a <form>
within this add a file element and a submit button. To enable selecting multiple files define multiple
attribute in file element.
Completed Code
<form method='post' action='' enctype='multipart/form-data'> <input type='file' name='files[]' multiple /> <input type='submit' value='Submit' name='submit' /> </form>
4. PHP
Create an upload
folder for storing the image files.
On the submit button click count total selected files and create a prepared statement for inserting the record in the images
table.
Loop on the files and extract the extension to check file is an image or not.
If it is image file then store it in upload
folder and execute the statement using execute()
method that pass an array while contains file name and path.
Completed Code
<?php include "config.php"; if(isset($_POST['submit'])){ // Count total files $countfiles = count($_FILES['files']['name']); // Prepared statement $query = "INSERT INTO images (name,image) VALUES(?,?)"; $statement = $conn->prepare($query); // Loop all files for($i=0;$i<$countfiles;$i++){ // File name $filename = $_FILES['files']['name'][$i]; // Location $target_file = 'upload/'.$filename; // file extension $file_extension = pathinfo($target_file, PATHINFO_EXTENSION); $file_extension = strtolower($file_extension); // Valid image extension $valid_extension = array("png","jpeg","jpg"); if(in_array($file_extension, $valid_extension)){ // Upload file if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$target_file)){ // Execute query $statement->execute(array($filename,$target_file)); } } } echo "File upload successfully"; } ?>
5. Conclusion
In the demonstration, I stored the uploaded image files path in the MySQL database table when the file successfully uploaded but you can also store the file in the base64 format in the field.
If you found this tutorial helpful then don't forget to share.