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 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 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 Select Multiple Files using HTML Input Tag ? Using the input tag to upload multiple files has become possible after the release of HTML 5. Since many of us, work on HTML and still use tags such as <input> tag for taking input from the user and <form> tag for using forms on our website, it is necessary to know how to implement multi
2 min read
How to access actual name of uploaded file in PHP ? In PHP, we can access the actual name of the file which we are uploading by keyword $_FILES["file"]["name"]. The $_FILES is the by default keyword in PHP to access the details of files that we uploaded.The file refers to the name which is defined in the "index.html" form in the input of the file.The
2 min read
How to Get Multiple Selected Values of Select Box in PHP? Given a list of items, the task is to retrieve the multiple selected values from a select box in PHP. Use multiple attributes in HTML to select multiple values from drop-down list. Selecting multiple values in HTML depends on operating system and browsers. For Windows users: hold down + CTRL key to
2 min read
How to check the Type and Size before File Uploading in PHP ? In PHP, it's essential to validate file types and sizes before allowing users to upload files to a server. This helps prevent potential security vulnerabilities and ensures that only allowed file types and sizes are accepted. PHP provides various methods to perform these validations, including check
2 min read