By storing media files in the MySQL database make it easier to retrieve files uploaded by the user or in a specific category.
For this require storing the file on the server and saving the reference to the database.
In the tutorial, I show how you can upload and store video to the MySQL database table with PHP. Also, show how you can display stored videos in the database.
Table of Content
- Create a Table
- Create a Database Configuration file
- Create a Video Upload Form and Store Video in the MySQL database
- Displaying Stored Videos from the Database with PHP
- Conclusion
1. Create a Table
Create videos
table.
CREATE TABLE `videos` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(255) NOT NULL, `location` varchar(255) NOT NULL );
2. Create a Database Configuration file
Create a config.php
file for the database configuration.
<?php session_start(); $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
3. Create a Video Upload Form and Store Video in the MySQL database
Create a new folder videos
at the project root.
HTML
Utilize $_SESSION['message']
to display the file upload response. Create a form containing a file input element and a submit button.
PHP
On <form >
submit assign max file size 5MB in bytes to $maxsize, this value can be adjusted as per your requirements.
Specify the file upload location to $target_dir
and determine the file extension, storing it in the $extension
variable.
Initialize the $extensions_arr
array with accepted video file extensions. If the file extension exists within this array, proceed to check the file size. If the file size is within the limits, proceed to upload the file and create a new record in the videos
table.
Assign the $name
variable to the name
field and $target_file
to the location
field in the database record.
<?php include("config.php"); if(isset($_POST['but_upload'])){ $maxsize = 5242880; // 5MB if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != ''){ $name = $_FILES['file']['name']; $target_dir = "videos/"; $target_file = $target_dir . $_FILES["file"]["name"]; // Select file type $extension = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Valid file extensions $extensions_arr = array("mp4","avi","3gp","mov","mpeg"); // Check extension if( in_array($extension,$extensions_arr) ){ // Check file size if(($_FILES['file']['size'] >= $maxsize) || ($_FILES["file"]["size"] == 0)) { $_SESSION['message'] = "File too large. File must be less than 5MB."; }else{ // Upload if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){ // Insert record $query = "INSERT INTO videos(name,location) VALUES('".$name."','".$target_file."')"; mysqli_query($con,$query); $_SESSION['message'] = "Upload successfully."; } } }else{ $_SESSION['message'] = "Invalid file extension."; } }else{ $_SESSION['message'] = "Please select a file."; } header('location: index.php'); exit; } ?> <!doctype html> <html> <head> <title>Upload and Store video to MySQL Database with PHP</title> </head> <body> <!-- Upload response --> <?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']); } ?> <form method="post" action="" enctype='multipart/form-data'> <input type='file' name='file' /> <input type='submit' value='Upload' name='but_upload'> </form> </body> </html>
4. Displaying Stored Videos from the Database with PHP
Create readfile.php
file to display the stored videos in the videos
table.
Retrieve all records stored in the videos
table.
Create a <video>
element and populate the src
attribute with the $location
value. Use a <span>
element to exhibit the video’s name.
<?php include("config.php"); ?> <!doctype html> <html> <head> <title>Upload and Store video to MySQL Database with PHP</title> </head> <body> <div> <?php $fetchVideos = mysqli_query($con, "SELECT * FROM videos ORDER BY id DESC"); while($row = mysqli_fetch_assoc($fetchVideos)){ $location = $row['location']; $name = $row['name']; echo "<div style='float: left; margin-right: 5px;'> <video src='".$location."' controls width='320px' height='320px' ></video> <br> <span>".$name."</span> </div>"; } ?> </div> </body> </html>
5. Conclusion
Store video file in a folder and insert file location in a MySQL database table. Display file using <video>
element.
Before defining the maximum file size for validation, it is essential to review the post_max_size
and upload_max_filesize
settings in the php.ini
file and make adjustments as necessary.
$maxsize = 5242880; // 5MB
How much is this? I did not understand what this conversion is.
5242880
Hello,thanks for sharing the code.I want to be able to upload videos of less than 500 MBs how do i go about it.Thank you
Hi If i have multiple images or videos it only shows the last one. How do i fix this?
Kind regards
Dries
sir video is not showing mean there is a voice and audio player just how can i fix this
Thank You!
It was very useful.
Please I tried your code but i want to upload up to 500 MB video please help . I eve tried other option you listed out but its not working am using WAMP SERVER
Hello,
How can i make it to play other video format like: mwv, m4a, flv, etc.
I put those video file extension in that extension array and yet, it does not play any of them. The video was properly uploaded and moved to the right folder.
Thank you sir,
I worked perfectly with me
your show the problem againts file size. i change the value php.ini but not work
Sir I try to upload a file of size 20MB but it always show me file is too large even I changed my XAMMP upload_max_size and post_max_filesize but it show me the smae line
Sir ffor 2mb file it is showing file is tooo large plz help me
This code is not work properly in my laptop
Any suggestion…??
The code works perfectly when uploading to the database but the comes when retrieving from the database the video doesnot play
Any help Mr . SIngh Thank you
Excellent Sir. Thank you so much.Works perfectly
Hi, This is a great article 🙂 one of the first well written articles Ive found on getting an upload function and got it working first time. Just wondered, as Im using bootstrap 4, how do I get it to display a popup box, for example using a Bootstrap Modals, saying success or failure and then redirect to another page?
when i want to insert the video with a foreign key i can’t insert the data to my phpmyadmin table. How can i insert the video with a foreign key. i’m using your’s source code
sorry i made some little mistake i didn’t check properly it works fine. Thanks for the source code.
Hello I have a challenge generating a certain php code .Below is a link to the problem I am trying to solve
https://dba.stackexchange.com/questions/264271/hot-to-generate-the-below-using-sql-and-codeigniter
I would be very happy if you can help please.Thank you
Thanks brother .
Thanks bro, it very useful for me. But can this upload coding, i use it as update code?
Please can you make how to convert a video from other video formats to HTML5 with PHP and FFMPEG before a user uploads the video. Similar to the one above, but little different of conversion.
Hi there,
I was hoping you could assist me with plugging some of your code into my existing code? I have the function working of uploading the file to the server (There are some issues still with the max file size, but I am hoping to sort this out with my ISP).
I need to upload another of fields from the form to the database as well as the video file location where it is saved, as later retrieve this and show it on another page.
Where can I share my code with you?
up to 20 mb video save to my database and folder. But when I upload 50 mb video file they didnot save in my database but save into folder. why
my php max upload size is 128mb
thank you so very much brother!!!
was an headache figuring this out…
move_uploaded_file – show No such file or directory in
Please Help me sir.
NEED HELP..!!
I have been playing with videos and trying to create a membership website for a few weeks. I just do not have it lol
Will anyone help create a site that does what I need and help out.
I do not have money but can advertise your programing on the site
I need a site that allows people to login and create a profile with a picture and video.
This is for an upcoming Virtual International Martial Arts Tournament
They will have to pay a fee using PayPal link and once they have paid they can upload their videos.
I then have judges 9th and 10th degree Masters and Grand Masters who will vote on the winners and they will be awarded prizes.
So I need a way for judges to review all profiles and put a grade or ranking on each video so if we have 12 judges a spot for each judge so everyone is looked at.
A way to pull a report of all the top winners
Grand Champion
20 1st place winners
30 2nd place winners
40 3rd place winners
50 4th place winners
60 5th place winners
But then a list of all coopetitors so we can send each one a digital Certificate for competing
I know this is beyond most programmers and is a lot to ask for free but I have seen so many tutorials that just look like this is all possible fairly easy for some of you 🙂
Please email me if your interested
If not I truly understand lol
Contact me through my email address… (istuff360@gmail.com)
very helpful
Thanks
Thanks alot. The code works perfectly fine – The best I’ve see so far.
Please, can you help with deleting the file from database/directory?
This didn’t work…
if (isset($_POST[“btn_delete”]))
{
$host =” “;
$uname =” “;
$pwd =” “;
$db_name =” “;
$name = $_POST[“name”];
$conn = mysqli_connect($host, $uname, $pwd, $db_name) or die(“Connection error: “. mysqli_error());
$query = “DELETE FROM `videos` WHERE `name` = $name”;
$result = mysqli_query($conn, $query);
if($result)
{
echo ‘Data Deleted’;
}else{
echo ‘Data Not Deleted’;
}
mysqli_close($connect);
}
What are the names of these files? How are they discovered by other files in the directory?
I’m confused?
POST Content-Length of 377970136 bytes exceeds the limit of 41943040 bytes in Unknown on line 0 ?? plese help while uploding more than 20MB size
I was wondering if what should the keyword I will search to arrange the Videos with padding, I successfully created this and all is working fine, What I want now is to add padding on each videos so they are organize like 5 videos in a row, and with a title,
I’ve search how to tablature data in php, but doesn’t give me what I need, I hope you can give me some tips on what to search about it, thank you for this by the way, I just learned php 15 minutes ago, and I already did this. Very easy to understand tutorial.
I tried it out and works fantastic. NOW I have one problem. I want to fit this in my existing website.
1. How do I use the style.css file to make it within my website and
2. the name of the video to be cut at the video box and continue on next line if the name is a long one.
Can you please show me how to do it?
Thanks