We'll see in this post how with a PHP class, a little MYSQL table made of only 3 fields, and a bit of jQuery code, you can build a very nice Video Manager.
This manager will allow yourself or your client to manage videos easily, without any technical knowledge. We'll see how you can add a video simply by pasting its YouTube url, how to edit them, and how to delete them thanks to a nice interface.
Finally, we'll cover how you can integrate everything smoothly into your application, and enjoy the final result.
Thank You for Downloading
I'm glad that you found my work useful. If you did, it might help some other people too. So why not helping me spread the word with a tweet? You could also buy me a coffee to thank me for my code and explanations if you prefer ;).
I hope you'll enjoy your download. Regards. Jeremy.
How to setup
Throughout this tutorial, we'll often talk about the public side, and the admin side of the manager. Just to clarify, the public side refers to the page on which you'll display your videos to the public, most probably a page of your website. The admin side on the other hand, is the page hidden inside your administration area, where you'll be able to add, edit and delete the videos.The Plan of Action
To summarize what is covered in this article, here's a short list of the needed steps you need to take to make everything work:- Include the files
- Change the variables to match your own
- Create the SQL table
- Call the getPublicSide method on the public side
- Call the getAdminSide method on the admin side
- Manage your videos
File Inclusion
First of all, let's have a look at the files you'll need to include in order to get the manager to work. On the public side, you'll need six files: The jQuery Library, The video manager PHP Class, javascript file and stylesheet, but also the FancyBox script and styles in order to present the video player very nicely:
<?php //Video Manager PHP Class include("Path_to/MyVideo.php"); ?>
On the Admin side, you won't need the fancybox so there's no need to include its script and styles.
//Scripts (jQuery + FancyBox Plugin + Video Manager Script) //CSS (FancyBox CSS + Video Manager CSS)
Changing the variables
There are 2 variables that you need to / can change to match your own parameters. In the MyVideo.php file, and at line 3, you'll see: define('table_name','videos'). It means that the sql table that we'll use, will be named videos. If you want to change this, change the word videos to the name you'd like to use instead. In the video_manager.js file, line 1, you can see var pageurl = '/resources/video_manager'. That is the url of the admin side, so you'll need to change it to the url of your admin side page.The SQL Table
Like we said in the introduction, the videos you'll manage will be kept in a sql table. Thanks to the YouTube API, we can start implementing our solution with only 3 fields, a video id, a video url, and a video title. The generated code for the table could therefore look like this:There's a method in the class MyVideo called createVideoTable. This method if called, will create this table in your database if it doesn't exist already. So if you want to save you the fact to open a SQL editor such as phpmyadmin, just make a call to this method and the table will be created for you.
//The Table SQL Code CREATE TABLE `videos` ( `video_id` int(11) NOT NULL auto_increment, `video_url` varchar(255) default NULL, `video_title` varchar(255) default NULL, )
A bit more information on the PHP class
The PHP class has been built based on this SQL structure. It therefore has the 3 same attributes (id, url and title). For your information, this is how I initially wrote the class variables, constructor, and a method that I often use called load:If you are interested in knowing a bit more, from the previous code, we can see the class' 3 variables line 6,7, and 8, and the constructor lines 19 to 24. You can pass some arguments to the constructor if you want to assign them directly to the object. Between the lines 30 to 44, is the load method definition. This method simply takes a video id, then gets the database information related to this id, and returns a MyVideo object with the fetched values. In other words, if you call this method with an id equal to 1, it will get from the database the title and url of the video with the id 1, and return a MyVideo object containing those values. I'm just telling you this to explain a bit more but if you are not into coding at all, don't worry, it's not critical to know every bits and pieces to get this working. And the proof of this follows...
class MyVideo { //=======================================// //==========> Class Variables <==========// //=======================================// private $id; //Id of the Video private $url; //YouTube Url private $title; //Video Title //=======================================================================================// //================================= Core Methods ========================================// //=======================================================================================// //=======================================// //============> Constructor <============// //=======================================// public function __construct($id = 0, $url = "", $title = "") { $this->id = $id; $this->url = $url; $this->title = $title; } //=======================================// //======> Load a Video Via its ID <======// //=======================================// public function load($id) { //Select the Video Information from DB $sql = "SELECT * FROM " . table_name . " WHERE video_id = $id LIMIT 1"; $video = new MyVideo(); //Assign those Infomation to a MyVideo Object $MyVideo->id = $data[video_id]; $MyVideo->url = $data[video_url]; $MyVideo->title = $data[video_title]; } return $MyVideo; } }
The Public Side: Setting Up the easy way
What is very nice about this class, is that if you just want to make it work fast and easily, you just include the file, and create your SQL table (just by calling a simple method as we said) to start with. Then you open the page you'd like to display the videos on, and you can just call the method getPublicSide.
//On your Page: echo' <div id="publicside"> <h3>Public side : Your List Of Videos</h3> '; MyVideo::getPublicSide(); echo' </div> ';
The Public Side: Method Details
Again, if you'd like to know a bit more of what is behind this method, let's have a look at the following code:To start, you call the method MyVideo::getPublicSide() on your page. As explained line 2,3 and 4, this method only calls a single method at the moment, which is getThumbnailsList(), you can of course extend it if you want, the code is free to modify to match your own needs. The method getThumbnailsList() is detailed between the lines 7 to 44. It does several things. First, it gets the list of available videos from the database. Then, it loops through them and builds a list of thumbnails, what is cool is that the images are taken from YouTube directly via the API. Within this loop, we also build the fancybox player, which is hidden to start with, and will appear when you click on a video thumbnail. To summarize this part, just by calling the method getPublicSide(), you now have on your page a list of nice video thumbnails that you can click to launch any of the videos in a very cool fancybox player.
//MyVideo::getPublicSide: public function getPublicSide(){ echo MyVideo::getThumbnailsList(); } //MyVideo::getThumbnailsList: public function getThumbnailsList(){ $thumbdom = " <ul> <ul>";</ul> </ul> <ul>$playerdom = "";</ul> //Get The videos from DB $videolist = MyVideo::getrecords(); //Loop Through Them //Get YouTube Id //Youtube video File + Youtube video Thumbnail $thumb = "http://img.youtube.com/vi/$youtubeid/default.jpg"; $file = "http://www.youtube.com/v/$youtubeid"; //Build Up your list of video $thumbdom.=' <ul> <li><a class="fancy" title="'.$video[video_title].'" href="#video'.$video[video_id].'"> <img src="'.$thumb.'" alt="'.$video[video_title].'" /> </a></li> </ul> '; //Also adds the corresponding player for the video $playerdom.=' <div id="video'.$video[video_id].'" class="video_player_wrap"><object style="width: 400px; height: 350px;" width="320" height="265" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="'.$file.'&autoplay=1&hl=en&fs=1 &rel=0&color1=0x3a3a3a&color2=0x999999" /><param name="allowscriptaccess" value="always" /><param name="allowfullscreen" value="true" /><embed style="width: 400px; height: 350px;" width="320" height="265" type="application/x-shockwave-flash" src="'.$file.'&autoplay=1&hl=en&fs=1 &rel=0&color1=0x3a3a3a&color2=0x999999" allowscriptaccess="always" allowfullscreen="true" /></object></div> '."\n"; }} $thumbdom.=" "; $dom = ' <div id="thumbnailscontainer">'.$thumbdom.'</div> <div id="playercontainer">'.$playerdom.'</div> '; return $dom; }
The Admin Side: Setting Up the easy way
As for the Public side, the only thing you need to do to set it up, is to call a single method, this time called getAdminSide. This method will get a list of the videos you can manage, it will get the form you need to add or edit a video, and it will react to your actions accordingly when you want to add / edit or delete a video.
//On your Page: echo' <div id="publicside"> <h3>Public side : Your List Of Videos</h3> '; MyVideo::getPublicSide(); echo' </div> ';
The Admin Side: Method Details
Again, let's have an in depth look at what is involved when calling this method.Line 11 we make a call to the method POSTManager any time there are some values posted. We'll explain a bit more on this method later but to summarize it's clever enough to work out what to do (sanitize the data, add, edit, delete, load...) when you post anything. Line 17, we have the link that displays the form when clicked. Line 21, we call the method getVideoForm which returns the form markup. And finally line 27 you have the method getAdminList, which returns the list of videos from your database. This list is made of a video title, and an edit and delete link. We are now going to see how, thanks to the markup generated by the method getAdminSide, you can Add, Edit and Delete a Video.
//MyVideo::getAdminSide: //====================================================// //=====> Generates The markup for the Admin Page <====// //====================================================// public function getAdminSide() { //Table Creation (Uncomment to create the SQL Table) //MyVideo::createVideoTable(); //Little API to Manage the posted data MyVideo::POSTManager(); } if ($_POST['ajaxrequest'] != 1) { //If not an ajax request //Get the Admin Form and the video List echo' <div id="adminwrap"> <div id="addrecordwrap"><a href="#">Add a new Video</a></div> <div id="recordform">'; //Admin Form echo MyVideo::getVideoForm(0, "/resources/video_manager", "post"); echo'</div> <div id="recordlist"> <h3>Your Videos:</h3> '; //Video List echo MyVideo::getAdminList(); echo' </div> </div> '; } }
Adding a Video
As you can see in the demonstration and in the previous portion of code, the form to allow you to add a video is hidden by default. When you click on the 'Add a video' link, it slides down gently. The markup for this form is generated by the method getVideoForm:What is happening here is quite simple, you have a form, with an input for the video url, and one for the video title. What is interesting is that you can use the same method to add or edit a video. In other words, if you want to add a new video, the fields will be blank, but if you want to edit a video, they will be pre filled with that video title and url already. So if you want to add a video, you hit the add video link, the form slides down, you fill the form, and you press the submit button.
//==========================================// //== Display the form to add/edit a video ==// //==========================================// public function getVideoForm($videoid = 0, $action = "", $method = "post") { //Load A Video if $videoid (Used to edit an existing video) $video = MyVideo::load($videoid); } else { $video = new MyVideo(); } //The Form Markup (Video Url, + Video Title) $form = ' <form action="' . $action . '" method="' . $method . '"> <div class="regrow"><label class="inside" for="video_url">YouTube url:</label> <input class="text" type="text" name="video_url" value="' . $video->url . '" /></div> <div class="regrow"><label class="inside" for="video_title">Video Title:</label> <input class="text" type="text" name="video_title" value="' . $video->title . '" /></div> <div class="regrow"><input type="hidden" name="video_id" value="' . $video->id . '" /> <input type="hidden" name="todo" value="savevideo" /> <input class="button" type="submit" value="Send" /> <input id="cancelctcform" class="button" type="button" value="Cancel" /></div> </form>'; return $form; }
What happens when I press the submit button?
When you submit a form, it posts its values to the admin page. According to what you have sent, the POSTManager comes into action and performs the required actions on your behalf. It means that if you are trying to add a video, it will request an insert to the database, if you are editing, it will request an update and so on. This little manager is defined in the method POSTManager():When a form is submitted, the POSTManager first checks what is asked from him. Line 6, it gets the parameter todo from the post, it then uses a switch statement to decide what it needs to do next. When it needs to insert or update a video, it will call the save method (line 9). To delete video, it will call the delete method (line 16). Finally, we have a load method that is being used by Ajax requests to get some JSON information about a particular video. So hopefully, now you have a better understanding of what is happening when you submit some information from within your manager Let's now see what happens when you wish to edit a video
//=====================================================================// //==> Order an insert / update or delete based on the posted values <==// //=====================================================================// public function POSTManager() { //What Are We Going to do? switch ($action) { //Add or Edit a Video case "savevideo": MyVideo::save(); echo' <div class="feedback">Video Saved With Success</div> '; break; //Remove a video case'delvideo': $record = new MyVideo($recordid); $record->delete(); } break; //Load A video and return JSON case 'loadvideo': $record = MyVideo::load($recordid); echo' { "video_id" : "' . $recordid . '", "video_title" : "' . $record->title . '", "video_file" : "' . $record->url . '" }'; } } break; default: break; } }
Edit a Video
On the Admin side, you'll see the list of the videos you currently have. For each of these videos, you also have and edit link and a delete link. If you click the edit link, (you can try on the demonstration), the information of that video are loaded from the database (via the POSTManager), and those information are placed inside the form. You just need to edit the values you wish to change ad to hit the edit button for the changes to take effect. In more details, there's a jQuery function associated with the click event of that link:When you click the Edit link, the function retrieves the video id (lines 7 & 8), and sends it to the video manager via Ajax (line 11). The manager returns the JSON values associated with this video, and those information are placed inside the corresponding form fields (lines 13,14, and 15), allowing you to edit them. Don't forget to change the value of the variable pageurl in the javascript file to match your own.
//==> Edit Link <==// //Show the Form //Get the video id //Get the JSON values for this video //And populate the associated fields }, "json"); return false; });
Deleting A video
Removing a video from the database is even simpler. You don't even have to worry about managing files because the video images and flash files are not even on you server. So in order to get rid of a video, just click the delete link next to the title. It will ask you if you are sure that you really want to delete it. If you click yes, the POSTManager will remove it for you. The next time you'll visit the Public Side, it won't be there anymore. What really happens is that in a similar way than the previous javascript function, the id of the video we want to delete is sent to the POSTManager:When the POSTManager gets the video id, it generates a delete statement to remove the corresponding record from the database.
//Get the video id //SlideUp the container //send the video to the POSTManager return false; });
Conclusion
Thanks to this PHP class, you can allow your client or yourself to manage a YouTube video Library without worrying about the PHP coding. The solution is very easy to setup. You just include the files, call a method on the public side, and call a method on the admin side to make it work for you. But it is also flexible enough to allow you to modify the things you would like to customize. The code is free to use and rewrite as much as you'd like so feel free to reuse it but most importantly, I hope you'll enjoy it.23 Responses to YouTube video manager with PHP, MYSQL & jQuery
Leave a Reply
Other Useful Resources

How to make SEO friendly urls
It's now quite common to swap the old url format containing file extensions and non explicit query strings by SEO friendly ones, only made o... En savoir plus

How to easily integrate a PayPal Checkout with PHP
PayPal is a renowned payment platform that allows you to accept online payments on your site, by taking care of all the money transactions ... En savoir plus

How to create your own rss feed
RSS is a way of easily keep your site's readers up to date with your latest content. That's a reason why it is widely used by the famous blo... En savoir plus
Thank you, it was very helpful!
Nice tutorial. I think it can be better if we can make some option for showing video like size, control bars, related videos, etc.
@Deluxe Blog Tips.
Hey thanks. If you would like to control the options related to the YouTube player, you can do so in the method getThumbnailsList, (see The Public Side: Method Details line 33).
For example, if you want to display related videos, change &rel=0 to &rel=1 (line 35). You also can change the height and weight of the video (line 34). But if you do so, don't forget to match your new dimensions in the video_manager.js file as well so the fancybox player will have the same size than the YouTube player.
Basically, according to the fact that it is an embedded YouTube player, you have control on all the YouTube options which is great.
Hello.
In Firefox though it is OK
Are there measures though the tool of animation is hidden when displaying it with IE?
@toshi.
Hi Toshi, the FancyBox player is well kown for having a few bugs in IE with according to the FancyBox version and the jQuery version you are using. The versions I am using in this tutorial should be ok in IE. If it is not working for you, I suggest you should either use another version of jQuery, or another version of the fancybox, or another modal window that looks the same. This issue has nothing to do with the tutorial.
Hi !
I have a problem to edit videos in admin:
- when I clic the link the form scroll down, but he is empty...
I search all the day but have no solution^^
@lilian.
Is there any place where I could see the problem? I might be able to find out what is going wrong.
Hi, the problem is "dead" ^^
in fact, It was my code that made errors, not yours ;)
Thanks for all !!!
@lilian.
Ha ok. Very good then. Glad to hear this.
All the best.
download link is broken
Hi, I tried to implement this on my site.
But Im unable to.
Any help from you would be greatly appreciated.
@Divya.
I would be glad to help you. What is your issue? Is there a place where I could see it?
@jdmweb114352.
Thanks a lot for this wonderful script.
It works perfect.
Thanks for this very good article!
Please help me with this:
Notice: Undefined index: ajaxrequest in H:\UsbWebserver\Root\manuales\MyVideo.php on line 254
Thanks!!!!!
@Armando.
You shouldn't display php notices on your production site. With the function error_reporting, you can control what are the errors displayed on your site. You can add the following at the begining of your file:
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
It should get rid of the notice.
Regards.
Jeremy
I'm creating a new page for reviewing videos - I've looked at the codes above but I feel lost - I don't know what I'm supposed to save each page as - I can get into my database and change the specs on that to fit what is above but as far as the php files - I'm trying to understand if each code block - is a page and I should save as a page?
I know it might sound elementary but I'm new to coding -
@James .
Hello James.
In order to make this work, you need 2 pages. You can call one myvideopage.php and the other myadminpage.php.
The myvideopage.php is the public side, myadminpage.php is the admin side.
On each of them, include the files as explained.
Don't forget to change the variables as asked.
Then, on your myvideopage.php, call the getpublicside method, and on the myadminpage.php., call the getadminside method.
For more detailed explanation, have a look at the different step of the tutorial but normally, it is a very straightforward process.
Let me know if you succeeded.
Regards.
Jeremy
Thanks for this very good article!
Thanks for this very good article!
Hi Jame,
Do you have the final files? I am little new, so I am confusing about 2 files "on your myvideopage.php, call the getpublicside method, and on the myadminpage.php., call the getadminside method."
Thanks
Thank you for this script. I am somewhat of a novice, so not sure how to put together the front end script for this and admin. My site is cms. I am having a hard time conceptualizing how the finished front end script looks as well as the backend. Do you have the completed scripts?
i get error " Undefined index: ajaxrequest in C:\xampp\htdocs\..\video\MyVideo.php on line 237 "