YouTube video manager with PHP, MYSQL & jQuery

video_manager
Youtube is the most popular platform when it comes to upload your videos to the web. It's therefore likely that some day, as a web developer, you'll be asked by one of your clients to integrate some YouTube videos on a web page or a social web app.

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:
  1. Include the files
  2. Change the variables to match your own
  3. Create the SQL table
  4. Call the getPublicSide method on the public side
  5. Call the getAdminSide method on the admin side
  6. 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:
  1. <?php //Video Manager PHP Class
  2. include("Path_to/MyVideo.php");
  3. ?>
  1. //Scripts (jQuery + FancyBox Plugin + Video Manager Script)
  2. <script type="text/javascript" src="Path_to/jquery.js"></script><script type="text/javascript" src="Path_to/jquery.fancybox.js"></script>
  3. <script type="text/javascript" src="Path_to/video_manager.js"></script>
  4.  
  5. //CSS (FancyBox CSS + Video Manager CSS)
On the Admin side, you won't need the fancybox so there's no need to include its script and styles.

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:
  1. //The Table SQL Code
  2. CREATE TABLE `videos` (
  3. `video_id` int(11) NOT NULL auto_increment,
  4. `video_url` varchar(255) default NULL,
  5. `video_title` varchar(255) default NULL,
  6. PRIMARY KEY (`video_id`)
  7. )
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.

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:
  1. define("table_name", "myvideos");
  2.  
  3. class MyVideo {
  4.  
  5. //=======================================//
  6. //==========> Class Variables <==========//
  7. //=======================================//
  8. private $id; //Id of the Video
  9. private $url; //YouTube Url
  10. private $title; //Video Title
  11.  
  12. //=======================================================================================//
  13. //================================= Core Methods ========================================//
  14. //=======================================================================================//
  15. //=======================================//
  16. //============> Constructor <============//
  17. //=======================================//
  18. public function __construct($id = 0, $url = "", $title = "") {
  19. $this->id = $id;
  20. $this->url = $url;
  21. $this->title = $title;
  22. }
  23.  
  24. //=======================================//
  25. //======> Load a Video Via its ID <======//
  26. //=======================================//
  27. public function load($id) {
  28. //Select the Video Information from DB
  29. $sql = "SELECT * FROM " . table_name . " WHERE video_id = $id LIMIT 1";
  30. $result = array();
  31. $video = new MyVideo();
  32. $req = mysql_query($sql) or die("Erreur SQL !" . $sql . "" . mysql_error());
  33.  
  34. //Assign those Infomation to a MyVideo Object
  35. while ($data = mysql_fetch_assoc($req)) {
  36. $MyVideo->id = $data[video_id];
  37. $MyVideo->url = $data[video_url];
  38. $MyVideo->title = $data[video_title];
  39. }
  40.  
  41. return $MyVideo;
  42. }
  43. }
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...

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.
  1. //On your Page:
  2. echo'
  3. <div id="publicside">
  4. <h3>Public side : Your List Of Videos</h3>
  5. ';
  6. MyVideo::getPublicSide();
  7. echo'
  8.  
  9. </div>
  10. ';

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:
  1. //MyVideo::getPublicSide:
  2. public function getPublicSide(){
  3. echo MyVideo::getThumbnailsList();
  4. }
  5.  
  6. //MyVideo::getThumbnailsList:
  7. public function getThumbnailsList(){
  8.  
  9. $thumbdom = "
  10. <ul>
  11. <ul>";</ul>
  12. </ul>
  13. &nbsp;
  14. <ul>$playerdom = "";</ul>
  15. //Get The videos from DB
  16. $videolist = MyVideo::getrecords();
  17.  
  18. //Loop Through Them
  19. if(!empty($videolist)){foreach($videolist as $video){
  20.  
  21. //Get YouTube Id
  22. $youtubeid = str_replace("watch?v=", "", end(explode("/", $video[video_url])));
  23. $youtubeid = reset(explode("&amp;", $youtubeid));
  24.  
  25. //Youtube video File + Youtube video Thumbnail
  26. $thumb = "http://img.youtube.com/vi/$youtubeid/default.jpg";
  27. $file = "http://www.youtube.com/v/$youtubeid";
  28.  
  29. //Build Up your list of video
  30. $thumbdom.='
  31. <ul>
  32. <li><a class="fancy" title="'.$video[video_title].'" href="#video'.$video[video_id].'">
  33. <img src="'.$thumb.'" alt="'.$video[video_title].'" />
  34. </a></li>
  35. </ul>
  36. &nbsp;
  37.  
  38. ';
  39.  
  40. //Also adds the corresponding player for the video
  41. $playerdom.='
  42. <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.'&amp;autoplay=1&amp;hl=en&amp;fs=1 &amp;rel=0&amp;color1=0x3a3a3a&amp;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.'&amp;autoplay=1&amp;hl=en&amp;fs=1 &amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999" allowscriptaccess="always" allowfullscreen="true" /></object></div>
  43. '."\n";
  44. }}
  45. $thumbdom.="
  46.  
  47. ";
  48. $dom = '
  49. <div id="thumbnailscontainer">'.$thumbdom.'</div>
  50. <div id="playercontainer">'.$playerdom.'</div>
  51. ';
  52. return $dom;
  53. }
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.

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.
  1. //On your Page:
  2. echo'
  3. <div id="publicside">
  4. <h3>Public side : Your List Of Videos</h3>
  5. ';
  6. MyVideo::getPublicSide();
  7. echo'
  8.  
  9. </div>
  10. ';

The Admin Side: Method Details

Again, let's have an in depth look at what is involved when calling this method.
  1. //MyVideo::getAdminSide:
  2. //====================================================//
  3. //=====&gt; Generates The markup for the Admin Page &lt;====//
  4. //====================================================//
  5. public function getAdminSide() {
  6. //Table Creation (Uncomment to create the SQL Table)
  7. //MyVideo::createVideoTable();
  8. //Little API to Manage the posted data
  9. if (!empty($_POST)) {
  10. MyVideo::POSTManager();
  11. }
  12. if ($_POST['ajaxrequest'] != 1) { //If not an ajax request
  13. //Get the Admin Form and the video List
  14. echo'
  15. <div id="adminwrap">
  16. <div id="addrecordwrap"><a href="#">Add a new Video</a></div>
  17. <div id="recordform">';
  18. //Admin Form
  19. echo MyVideo::getVideoForm(0, "/resources/video_manager", "post");
  20. echo'</div>
  21. <div id="recordlist">
  22. <h3>Your Videos:</h3>
  23. ';
  24. //Video List
  25. echo MyVideo::getAdminList();
  26. echo'
  27.  
  28. </div>
  29. </div>
  30. ';
  31. }
  32. }
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.

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:
  1. //==========================================//
  2. //== Display the form to add/edit a video ==//
  3. //==========================================//
  4. public function getVideoForm($videoid = 0, $action = "", $method = "post") {
  5. //Load A Video if $videoid (Used to edit an existing video)
  6. if ((!empty($videoid)) &amp;&amp; (is_numeric($videoid))) {
  7. $video = MyVideo::load($videoid);
  8. } else {
  9. $video = new MyVideo();
  10. }
  11.  
  12. //The Form Markup (Video Url, + Video Title)
  13. $form = '
  14.  
  15. <form action="' . $action . '" method="' . $method . '">
  16. <div class="regrow"><label class="inside" for="video_url">YouTube url:</label>
  17. <input class="text" type="text" name="video_url" value="' . $video-&gt;url . '" /></div>
  18. <div class="regrow"><label class="inside" for="video_title">Video Title:</label>
  19. <input class="text" type="text" name="video_title" value="' . $video-&gt;title . '" /></div>
  20. <div class="regrow"><input type="hidden" name="video_id" value="' . $video-&gt;id . '" />
  21. <input type="hidden" name="todo" value="savevideo" />
  22. <input class="button" type="submit" value="Send" />
  23. <input id="cancelctcform" class="button" type="button" value="Cancel" /></div>
  24. </form>';
  25. return $form;
  26. }
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.

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():
  1. //=====================================================================//
  2. //==&gt; Order an insert / update or delete based on the posted values &lt;==//
  3. //=====================================================================//
  4. public function POSTManager() {
  5. //What Are We Going to do?
  6. $action = htmlentities($_POST['todo'], ENT_QUOTES);
  7. switch ($action) {
  8. //Add or Edit a Video
  9. case "savevideo": MyVideo::save();
  10. echo'
  11. <div class="feedback">Video Saved With Success</div>
  12. ';
  13. break;
  14.  
  15. //Remove a video
  16. case'delvideo':
  17. $recordid = htmlentities($_POST['recordid'], ENT_QUOTES);
  18. if (!empty($recordid)) {
  19. $record = new MyVideo($recordid);
  20. $record-&gt;delete();
  21. }
  22. break;
  23.  
  24. //Load A video and return JSON
  25. case 'loadvideo':
  26. $recordid = htmlentities($_POST['recordid'], ENT_QUOTES);
  27. if (!empty($recordid)) {
  28. $record = MyVideo::load($recordid);
  29. if (!empty($record)) {
  30. echo'
  31. {
  32. "video_id" : "' . $recordid . '",
  33. "video_title" : "' . $record-&gt;title . '",
  34. "video_file" : "' . $record-&gt;url . '"
  35. }';
  36. }
  37. }
  38. break;
  39. default: break;
  40. }
  41. }
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

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:
  1. //==&gt; Edit Link &lt;==//
  2. jQuery(".editvideolink").click(function(){
  3. //Show the Form
  4. jQuery("#recordform").slideDown();
  5.  
  6. //Get the video id
  7. var wrap_ = jQuery(this).parent();
  8. var recordid = jQuery(wrap_).attr("id").split("_")[1];
  9.  
  10. //Get the JSON values for this video
  11. jQuery.post(pageurl, {todo:"loadvideo", recordid:recordid}, function(data){
  12. //And populate the associated fields
  13. jQuery("#recordform form input[name=video_id]").val(data.video_id);
  14. jQuery("#recordform form input[name=video_url]").val(data.video_file);
  15. jQuery("#recordform form input[name=video_title]").val(data.video_title);
  16. }, "json");
  17. return false;
  18. });
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.

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:
  1. jQuery(".confdel").livequery("click", function(){
  2. //Get the video id
  3. var wrap_ = jQuery(this).parent();
  4. var recordid = jQuery(wrap_).attr("id").split("_")[1];
  5.  
  6. //SlideUp the container
  7. jQuery(wrap_).slideUp("slow");
  8.  
  9. //send the video to the POSTManager
  10. jQuery.post(pageurl, {todo:"delvideo", recordid:recordid}, function(data){});
  11. return false;
  12. });
When the POSTManager gets the video id, it generates a delete statement to remove the corresponding record from the database.

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

  1. Jen

    Thank you, it was very helpful!

  2. Deluxe Blog Tips

    Nice tutorial. I think it can be better if we can make some option for showing video like size, control bars, related videos, etc.

  3. author jdmweb

    @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.

  4. toshi

    Hello.

    In Firefox though it is OK
    Are there measures though the tool of animation is hidden when displaying it with IE?

  5. author jdmweb

    @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.

  6. lilian

    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^^

  7. author jdmweb

    @lilian.
    Is there any place where I could see the problem? I might be able to find out what is going wrong.

  8. lilian

    Hi, the problem is "dead" ^^
    in fact, It was my code that made errors, not yours ;)
    Thanks for all !!!

  9. author jdmweb

    @lilian.
    Ha ok. Very good then. Glad to hear this.
    All the best.

  10. lenamtl

    download link is broken

  11. Divya

    Hi, I tried to implement this on my site.
    But Im unable to.
    Any help from you would be greatly appreciated.

  12. author jdmweb

    @Divya.
    I would be glad to help you. What is your issue? Is there a place where I could see it?

  13. Divya

    @jdmweb114352.
    Thanks a lot for this wonderful script.
    It works perfect.

  14. gta 5

    Thanks for this very good article!

  15. Armando

    Please help me with this:

    Notice: Undefined index: ajaxrequest in H:\UsbWebserver\Root\manuales\MyVideo.php on line 254

    Thanks!!!!!

  16. author jdmweb

    @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

  17. James

    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 -

  18. author jdmweb

    @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

  19. camfito

    Thanks for this very good article!

  20. camfito

    Thanks for this very good article!

  21. Diana

    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

  22. ks

    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?

  23. Mohit

    i get error " Undefined index: ajaxrequest in C:\xampp\htdocs\..\video\MyVideo.php on line 237 "

Leave a Reply

*

Other Useful Resources