How to Upload Multiple Images and Text to MySQL Database in PHP?
Last Updated :
30 Apr, 2024
In web development, many times we need to handle multiple files at once while uploading and storing into the database. So in this article, we will see how to do this by various approaches to achieve this using PHP and MySQL.
Approach 1: Storing Images in the File System
In this approach, the images are uploaded to a server directory, and their paths are stored in the database. This method is good for handling large volumes of images and allows for easily management of files.
Step 1: HTML Form for Uploading Multiple Images
<form action="file1.php" method="post" enctype="multipart/form-data">
<input type="file" name="images[]" multiple>
<input type="text" name="text_data">
<input type="submit" name="submit" value="Upload">
</form>
Step 2: PHP Script to Handle Uploads and Database Insertion
$targetDir = "images/";
foreach ($_FILES['images']['name'] as $key => $value) {
$fileName = basename($_FILES['images']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
move_uploaded_file($_FILES["images"]["tmp_name"][$key], $targetFilePath));
}
$stmt = $conn->prepare("INSERT INTO tbl_images (img_url, img_txt) VALUES (?, ?)");
Step 3: Create a Database Table
CREATE TABLE images_table (
id INT AUTO_INCREMENT PRIMARY KEY,
img_url VARCHAR(255) NOT NULL,
img_txt TEXT NOT NULL
);
- Here we using a HTML forms to upload images along with text data.
- In the PHP script, move the uploaded file to the "images" directory and retrieve its file path.
- Then making an SQL query to insert the file path and text data into the database.
Example:
PHP
<?php
include_once("conn.php");
if (isset($_POST["submit"])) {
$stmt = $conn->prepare("INSERT INTO tbl_images (img_url, img_txt) VALUES (?, ?)");
$stmt->bind_param("ss", $imagePath, $textData);
$uploadedImages = $_FILES['images'];
$textData = $_POST['text_data'];
foreach ($uploadedImages['name'] as $key => $value) {
$targetDir = "images/";
$fileName = basename($uploadedImages['name'][$key]);
$targetFilePath = $targetDir . $fileName;
if (file_exists($targetFilePath)) {
echo "Sorry, file already exists.<br>";
} else {
if (move_uploaded_file($uploadedImages["tmp_name"][$key], $targetFilePath)) {
$imagePath = $targetFilePath;
$stmt->execute();
echo "The file " . $fileName . " has been uploaded successfully.<br>";
} else {
echo "Sorry, there was an error uploading your file.<br>";
}
}
}
$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Image Upload 1</title>
</head>
<body>
<br><br>
<form action="file1.php" method="post"
enctype="multipart/form-data">
Select Image Files:
<input type="file" name="images[]" multiple>
<br><br>
<input type="text" name="text_data">
<br><br>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Output:
image upload 1Approach 2: Using Base64 Encoding
Another way is base64 encoding, images are converted to a string format and stored directly in the database. This approach simplifies file management but may increase database size and retrieval time.
Step 1: HTML Form for Uploading Multiple Images
<form action="file1.php" method="post" enctype="multipart/form-data">
<input type="file" name="images[]" multiple>
<input type="text" name="text_data">
<input type="submit" name="submit" value="Upload">
</form>
Step 2: PHP Script to Handle Image upload, incoding and Database Insertion
foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
$imageData = base64_encode(file_get_contents($tmp_name));
$stmt = $conn->prepare("INSERT INTO tbl_images2 (img_data, img_txt) VALUES (?, ?)");
}
Step 3: Create a Database Table
CREATE TABLE tbl_images2 (
id INT AUTO_INCREMENT PRIMARY KEY,
img_data MEDIUMTEXT NOT NULL,
img_txt TEXT NOT NULL
);
- Created a database table with a column to store base64 encoded image data.
- Using HTML forms to upload images.
- In the PHP script, encode the uploaded image to base64 format and store it directly in the database.
Example:
PHP
<?php
include_once("conn.php");
if (isset($_POST["submit"])) {
$stmt = $conn->prepare("INSERT INTO tbl_images2 (img_data, img_txt) VALUES (?, ?)");
$stmt->bind_param("ss", $imageData, $textData);
$uploadedImages = $_FILES['images'];
$textData = $_POST['text_data'];
foreach ($uploadedImages['tmp_name'] as $key => $tmp_name) {
$imageData = base64_encode(file_get_contents($tmp_name));
$stmt->execute();
echo "The file " . $fileName = basename($uploadedImages['name'][$key])
. " has been uploaded successfully.<br>";
}
$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Uplaod 2</title>
</head>
<body>
<br><br>
<form action="file2.php" method="post" enctype="multipart/form-data">
Select Image Files:
<input type="file" name="images[]" multiple>
<br><br>
<input type="text" name="text_data">
<br><br>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Output:
Php image upload 2
Similar Reads
How to Update Data in MySQL Database Table Using PHP?
Updating data in a MySQL database table using PHP is a fundamental aspect of web development, particularly in applications where user interactions involve modifying existing records. This guide delves into the process of updating data in a MySQL database table using PHP, covering database connection
3 min read
How to upload images in MySQL using PHP PDO ?
In this article, we will upload images to the MySQL database using PHP PDO and display them on the webpage. Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this tutorial, we will be using the WAMP server. Article content: Table StructureDatabase configuratio
5 min read
How to Insert JSON data into MySQL database using PHP?
To insert JSON data into MySQL database using PHP, use the json_decode function in PHP to convert JSON object into an array that can be inserted into the database. Here, we are going to see how to insert JSON data into MySQL database using PHP through the XAMPP server in a step-by-step way. JSON Str
3 min read
How to Upload Single/Multiple Image to Cloudinary using Node.js ?
Uploading images to Cloudinary from a Node.js application is a common task when you need to manage and store images in the cloud. Cloudinary is a cloud-based service that provides comprehensive solutions for image and video management, including upload, storage, manipulation, and delivery.Approachto
4 min read
How to change the maximum upload file size in PHP ?
The maximum size of any file that can be uploaded on a website written in PHP is determined by the values of max_size that can be posted or uploaded, mentioned in the php.ini file of the server. In case of hosted server need to contact the administrator of the hosting server but XAMPP has interprete
2 min read
How to match username and password in database in SQL ?
In this article, we are going to check the credentials (username and password) entered by the user. If credentials are matched from the database entries, the user can enter into another page and if credentials are incorrect then it displays "Sorry Invalid Username and Password". Pre-requisites: XAMP
4 min read
How to Install WordPress on the Linux Apache MySQL and PHP stack ?
WordPress is one of the commonly used Content Management systems on the web. It is written in PHP web servers like Apache are enough to run it. WordPress supports MySQL and MariaDB, but MySQL is widely used. This tutorial will help you to run WordPress using the LAMP(Linux, Apache, MySQL, PHP) stack
8 min read
How to retrieve data from MySQL database using PHP ?
There are steps to understand for retrieving the data from the MySQL database. Approach: Create the database, then create the table for data.Enter the rows in the table. You have to connect to the database. Now we understand each and every step as shown below.  Example 1: In this. we use PHPMyAdmin
2 min read
How to upload an image using HTML and JavaScript in firebase ?
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud st
3 min read
How to make a Todo App using PHP & MySQL ?
To create a Todo App using PHP and MySQL, you'll first need to set up a MySQL database to store the tasks. Then, use PHP to create a web interface where users can add, edit, and delete tasks. PHP will handle the backend logic, such as connecting to the database and performing CRUD operations. Finall
4 min read