How To Upload Files In PHP And Store In MySql Database
Let’s Upload the files using the PHP and save the files to the MySql database.
But wait, We are not going to save the file to the MySql database, We will only save the file path into the database and file will be store at the server folder.
By using the database we can store the file path and retrieve the file path whenever we need it.
PHP Upload Files And Store In The MySql Database Source Code:
if(isset($_POST["btnSubmit"])){ $errors = array(); $extension = array("jpeg","jpg","png","gif"); $bytes = 1024; $allowedKB = 100; $totalBytes = $allowedKB * $bytes; if(isset($_FILES["files"])==false) { echo "<b>Please, Select the files to upload!!!</b>"; return; } $conn = mysqli_connect("localhost","root","","phpfiles"); foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) { $uploadThisFile = true; $file_name=$_FILES["files"]["name"][$key]; $file_tmp=$_FILES["files"]["tmp_name"][$key]; $ext=pathinfo($file_name,PATHINFO_EXTENSION); if(!in_array(strtolower($ext),$extension)) { array_push($errors, "File type is invalid. Name:- ".$file_name); $uploadThisFile = false; } if($_FILES["files"]["size"][$key] > $totalBytes){ array_push($errors, "File size must be less than 100KB. Name:- ".$file_name); $uploadThisFile = false; } if(file_exists("Upload/".$_FILES["files"]["name"][$key])) { array_push($errors, "File is already exist. Name:- ". $file_name); $uploadThisFile = false; } if($uploadThisFile){ $filename=basename($file_name,$ext); $newFileName=$filename.$ext; move_uploaded_file($_FILES["files"]["tmp_name"][$key],"Upload/".$newFileName); $query = "INSERT INTO UserFiles(FilePath, FileName) VALUES('Upload','".$newFileName."')"; mysqli_query($conn, $query); } } mysqli_close($conn); $count = count($errors); if($count != 0){ foreach($errors as $error){ echo $error."<br/>"; } } }
Display Uploaded Files Source Code:
<h3>Uploaded Files:</h3> <br/> <?php $conn = mysqli_connect("localhost","root","","phpfiles"); $query = "SELECT *FROM UserFiles"; $result = mysqli_query($conn, $query); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $url = $row["FilePath"]."/".$row["FileName"]; ?> <a href="<?php echo $url; ?>"><image src="<?php echo $url; ?>" class="images" /></a> <?php } } else { ?> <p>There are no images uploaded to display.</p> <?php } ?>
Click here to download full source code
How to use demo:
First Create the Table UserFiles in the phpMyAdmin MySql database.
Put the downloaded project WWW folder of the WAMP/XAMPP.
- Create database named PHPFiles in the phpMyAdmin(MySql).
- Exatract the downloaded project.
- Find the phpfiles.sql file inside the DbBackup folder.
- Import the phpFiles.sql script to the create the table into the MySql.
Or you can directly create the table. Create the following structure MySql table:
Click here to download full source code

UserFiles table structure