File Upload To MySQL
File Upload To MySQL
File Upload To MySQL
MySQL
upload and store the image file in MySQL database using PHP.
The example code demonstrates the process to implement the file upload functionality
in the web application and the following functionality will be implemented.
HTML form to upload image.
Upload image to server using PHP.
Store file name in the database using PHP and MySQL.
Retrieve images from the database and display in the web page.
To store the image file name a table need to be created in the database. The following
SQL creates an images table with some basic fields in the MySQL database.
The dbConfig.php file is used to connect and select the MySQL database. Specify the
database hostname ( $dbHost ), username ( $dbUsername ), password ( $dbPassword ),
and name ( $dbName ) as per your MySQL credentials.
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld_db";
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Create an HTML form to allow the user to choose a file they want to upload. Make sure
<form> tag contains the following attributes.
method="post"
enctype="multipart/form-data"
The file upload form will be submitted to the upload.php file to upload image to the
server.
The upload.php file handles the image upload functionality and shows the status
message to the user.
Include the database configuration file to connect and select the MySQL database.
Get the file extension using pathinfo() function in PHP and validate the file format to check
whether the user selects an image file.
Upload image to server using move_uploaded_file() function in PHP.
Insert image file name in the MySQL database using PHP.
Upload status will be shown to the user.
<?php
// Include the database configuration file
include_once 'dbConfig.php';
$statusMsg = '';
if(isset($_POST["submit"])){
if(!empty($_FILES["file"]["name"])){
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
Now we will retrieve the uploaded images from the server based on the file names in
the database and display images in the web page.
Include the database configuration file.
Fetch images from MySQL database using PHP.
List images from the uploads directory of the server.
<?php
// Include the database configuration file
include 'dbConfig.php';