Add thumbnail to video – PHP & FFmpeg

Thumbnail is basically a preview of video. Every operating system by default add a thumbnail to a video by itself. When you open YouTube, every video you must have see an image along with it’s title. It gives the preview of video and tells what the video is about. Most people use custom images as thumbnail and most are automatically generated by YouTube.

Default video thumbnail

When it comes to operating system, you have a lot of video files in your hard drive and you can see little images that gives the insight of each video. Thumbnail of those videos are automatically generated by operating system itself. The thumbnail assign by OS comes from one of the frames inside the video. Which means the image you see on video thumbnail must have appeared somewhere in the video. “You can change it”

In order to change that thumbnail, you must have FFmpeg installed in your system. You can download it from it’s official site. We are creating a form that will allow you to select video whose thumbnail needs to be changed and image which will be used as new thumbnail.

Creating layout

<link rel="stylesheet" href="bootstrap-darkly.min.css">

<div class="container" style="margin-top: 100px;">
	<div class="col-md-6 offset-md-4">
		<form method="POST" enctype="multipart/form-data" action="add-thumbnail.php">

			<div class="form-group">
				<label>Select video</label>
				<input type="file" name="video" accept="video/*" required class="form-control">
			</div>

			<div class="form-group">
				<label>Select image</label>
				<input type="file" name="image" accept="image/*" required class="form-control">
			</div>

			<input type="submit" class="btn btn-primary" value="Add thumbnail">

		</form>
	</div>
</div>

Processing the form

At this point if you run the script, you will see a form with 2 input fields and a submit button. One input field is for selecting video and second is for selecting image. Now you need to create a new file named “add-thumbnail.php” and paste the following code in it:

<?php

$video = $_FILES["video"]["tmp_name"];
$image = $_FILES["image"]["tmp_name"];

$command = "/usr/local/bin/ffmpeg -i $video -i $image -map 0 -map 1 -c copy -c:v:1 png -disposition:v:1 attached_pic output.mp4";
system($command);

echo "Thumbnail has been added";
?>

Now you can run the script and you will see a form with 2 input fields, one for video and one for image. Select the video of your choice and select image from other field. When you hit the submit button, you will see a new file will be created at the root of your project’s folder named “output.mp4”. The newly created video file will have the thumbnail of your selected image file. All other attributes of video (bitrate, resolution, buffer size etc) will remain same.

I have also attached all the source files below, make sure you download them and let us know if you face any issue.

Select thumbnail from video

We created a detailed post on how you can generate thumbnails from a video. After you have generated all the thumbnails, you can add the thumbnail as per your choice.

[wpdm_package id=’158′]

Compress video in bitrate and resolution – PHP & FFmpeg

You can compress the video by bitrate and by resolution in PHP and FFmpeg. You can download FFmpeg from here. Compressing will save you some space in your system.

Compress video in bitrate and resolution – PHP & FFmpeg

When it comes in compressing the video, there are many options which can be adopted. The most basic and effective one is to decrease the bitrate of video. Changing bitrate will result in decreasing the quality of video, thus will reduce the size of video. Decreasing the quality of video will help you in easily transfer the file over the internet. Lower size video will consume less bandwidth and transfer faster than large size videos.

4k

The highest quality video having highest bitrate value is 4K as of writing this today. 4K display also known as the retina display because it gives the clear picture of video as you see with naked eye. Not 3D of course, but talking in terms of quality. Similarly, the least quality video having lowest bitrate value is 144P and it looks good on small screens only. In fact, there are very few devices with such small screen are left today.

So in the near future, this quality most probably be removed at all from the quality format table. Most of the movies you see in Blu-ray are usually in 720P or in 1080P, these are also known as high definition videos HD. As of today, we also have 2K and 4K display but you do not really wanted to compress the video to 2K. Usually you want high quality video to compress to lower quality.

Video’s bitrate and their format

BitrateFormat
350k240p
700k360p
1200k480p
2500k720p
5000k1080p

Another option to compress the video is to change it’s resolution. Resolution in videos is defined by their width and height (w x h), also known as dimension of video. The 4K display usually have the resolution of 2560 x 1600 which you can get in Macbook Pro 2017 and onwards. Decreasing the resolution of video is useful especially when you wanted to view the video in small screens. For example, you have a video in 2560 x 1600 resolution and you wanted to see this in mobile phone. Playing such high resolution video in mobile devices sometimes makes the device run slow, since not all mobile phones have such high processing speeds. Moreover, playing the video in 1200 x 720 resolution is enough to view it in high quality in small screens. There are some phones which can play 1920 x 1080 video seamlessly.

YouTube

When it comes to uploading the video on YouTube, it is recommended to upload the video to at-least 720P which means the video dimension must be at-least 1200 x 720. If you have a video of 720P then YouTube will automatically gives users an option to view the video in lower formats and it also gives your video an HD tag which will be seen on bottom right corner of video thumbnail. So if you have any device that can record 4K video, Macbook Pro or Panasonic or DSLR, you can create the video in 4K but later can reduce the resolution to 1080 or 720P without having the fear to lose the quality of video.

Compress video by bitrate

<link rel="stylesheet" type="text/css" href="bootstrap-darkly.min.css">

<div class="container" style="margin-top: 200px;">
    <div class="row">
        <div class="col-md-4 offset-md-4">
            <h1>Change bitrate</h1>

            <form method="POST" enctype="multipart/form-data" action="change-bitrate.php">
                <div class="form-group">
                    <label>Select video</label>
                    <input type="file" name="video" class="form-control" required="" accept="video/*">
                </div>

                <div class="form-group">
                    <label>Select bitrate</label>
                    <select name="bitrate" class="form-control">
                        <option value="350k">240p</option>
                        <option value="700k">360p</option>
                        <option value="1200k">480p</option>
                        <option value="2500k">720p</option>
                        <option value="5000k">1080p</option>
                    </select>
                </div>

                <input type="submit" name="change_bitrate" class="btn btn-info" value="Change bitrate">
            </form>
        </div>
    </div>
</div>

Now we need to create a page that will process this request. So create a new file named “change-bitrate.php” and paste the following code in it:

<?php

$video = $_FILES["video"]["tmp_name"];
$bitrate = $_POST["bitrate"];

$command = "/usr/local/bin/ffmpeg -i $video -b:v $bitrate -bufsize $bitrate output.mp4";
system($command);

echo "File has been converted";

Compress video by resolution

<div class="container" style="margin-top: 50px; margin-bottom: 100px;">
	<div class="row">
		<div class="col-md-4 offset-md-4">
			<h1>Change resolution</h1>

			<form method="POST" enctype="multipart/form-data" action="change-resolution.php">
				<div class="form-group">
					<label>Select video</label>
					<input type="file" name="video" class="form-control" required="">
				</div>

				<div class="form-group">
					<label>Select resolution</label>
					<input type="text" name="resolution" class="form-control" placeholder="640x480">
				</div>

				<input type="submit" name="change_resolution" class="btn btn-info" value="Change resolution">
			</form>
		</div>
	</div>
</div>

change-resolution.php

<?php

$video = $_FILES["video"]["tmp_name"];
$resolution = $_POST["resolution"];

$command = "/usr/local/bin/ffmpeg -i $video -s $resolution output2.mp4";
system($command);

echo "File has been converted";

Now you can run the script in your browser and you will be able to change the resolution of selected video file. The original file won’t get affected, there will always be a new file created separately with compressed bitrate or resolution. When you reduce the resolution of video, then it may have a slight effect on video size. For example, 1920 x 1080 video will be compressed to 1280 x 720 but the size of video may have been reduced to just 2 or 3 MB. This is because changing the resolution does not reduct the quality of video, it just convert the high resolution video into low resolution. This is useful when you wanted to see the videos in small screen or when you wanted to share your video on social network.

That’s all for now. I have also attached all the source files below, make sure you download them and let us know if you face any issue.

Save space by splitting video

If you have a video of very large size. And you are having problem in moving it from one hard drive to another. You can split the video in multiple parts. Learn how to do it.

[wpdm_package id=’156′]

Add or extract audio from video – PHP & FFmpeg

In this article, we are going to teach you how you can add audio to a video. And also, how you can extract the audio from the video. We will be using PHP and FFmpeg for both purposes.

Add audio to video

Adding audio to a video will replace the video’s actual audio. You can use it to either replace the video’s audio. Or wanted to put some background music on any of your video. Each video has audio input streams which we can hear when we play the video. If you have ever watched any video that does not have any sound. It means the number of audio steams in that file is 0.

You can add any audio to your video by first removing the audio streams from video file. And then get the audio streams from audio file. And put them on the video file. We will be creating a separate file for output that will contain your video and new audio. Because we do not wanted to make any changes in the original file. You just needs to remember that the length of output file will be equal to the length of maximum media stream.

For example, if audio length is 10 seconds and video length is 15 seconds, the new output will be of 15 seconds. That is why it is a good practice to make the length of both files to be equal. If you have files of unequal lengths, you can always trim the video or audio to required length by following this tutorial. You can also try to keep audio streams from both (audio and video).

You may have seen it in some videos that has the actual sound of the video and they also have a very little, dim music in the background. These type of videos are best for explaining historical facts or world’s cultures etc.

Extract audio from video

Aside from adding music track, sometimes you want to extract an audio. You have a video song in your computer but cannot play that in music player. Because it is a video, you can convert that to audio and then listen that as audio file. As mentioned above, it will not affect your original video file. It will create a separate file with just audio in it. You are watching an action or thriller movie and you want to extract some of music track from it, you can first extract that specific part from video by following this tutorial and then convert that extracted video to audio.

Add music track to video

We will be using bootstrap darkly for layout and design, it will be included in the source files below. Below is the code that will create a simple form with 2 input fields. The first input field will be to select video where music track needs to be added. The second is the mp3 file which will be the music file that needs to be added in the background of selected video.

<link rel="stylesheet" href="bootstrap-darkly.min.css">

<div class="container" style="margin-top: 100px;">
    <div class="row">
        <div class="offset-md-4 col-md-4">
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Select video</label>
                    <input type="file" name="video" class="form-control" required>
                </div>

                <div class="form-group">
                    <label>Select audio</label>
                    <input type="file" name="audio" class="form-control" required>
                </div>

                <input type="submit" class="btn btn-success" value="Add Audio">
            </form>
        </div>
    </div>
</div>

Now we need to process the form data and replace the video’s actual audio with a selected music track. Paste the following code at the top or bottom of your PHP file:

<?php

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        $video = $_FILES["video"]["tmp_name"];
        $audio = $_FILES["audio"]["tmp_name"];

        $command = "/usr/local/bin/ffmpeg -i " . $video . " -i " . $audio . " -c:v copy -map 0:v:0 -map 1:a:0 output.mp4";
        system($command);

        $command = "/usr/local/bin/ffmpeg -i " . $video . " original-audio.mp3";
        system($command);
    }

?>

Extracting audio

At this point, we have replaced the video’s actual audio with selected music. Now we wanted to extract the actual audio. This will also be useful if you wanted to convert any video song into mp3 file. This will not only save your memory but also helps in listening the song in your mp3 player or iPod, which otherwise you won’t be able to do. To extract audio from selected video you just needs to run another command right below your system function call.

$command = "/usr/local/bin/ffmpeg -i " . $video . " original-audio.mp3";
system($command);

This is the simplest command you will see related to FF mpeg, after telling the complete path of FF mpeg you just needs to tell the input video file and then the name of output audio file which we are naming as “original-audio.mp3”. This will create a separate mp3 file with the music of selected video. But if you want to convert the audio in some specific format, then you can use the following command:

$command = "/usr/local/bin/ffmpeg -i " . $video . " -b:a 192K -vn original-audio.mp3";
system($command);

This will convert the audio in 192 bitrate format. Change that value to any you want but the basic acceptable formats are 64K, 96K, 128K, 196K and 320K. 320K is the highest and best quality audio format today.

I have also attached all the source files below, make sure you download them and let us know if you face any issue.

[wpdm_package id=’154′]

Merge multiple videos in one file – PHP & FFmpeg

Merge or combining multiple short videos in one long file is usually done by some of the softwares available on the internet. Some operating systems provides basic editing softwares for free, for example Windows 10 has built-in video editor in their Windows Media Player. Macintosh has QuickTime player and iMovie which came along with operating system for free. If you do not have such editor you can always download from the internet and sometimes you have to pay some amount because some of them are not free. In this tutorial, we will be creating a simple PHP script that will help you to combine multiple video and save them in one file as a separate video.

Step 1 – Download FFmpeg

First you need to download and install FFmpeg encoder which you can download from here: Download FFmpeg. This encoder is used to edit video and audio files, you can edit MP4/FLV/MKV/3GP or MOV files. You can edit all types of audio files from this too including MP3, WAV or OGG. FFmpeg is basically a command line tool so after installation try to run the command in your terminal or command prompt:

> ffmpeg

This will make sure FFmpeg has been installed perfectly in your system. Now you can use it’s commands, you can find all documentation in it’s official website.

Step 2 – Creating layout

The design is quite simple, we will be using bootstrap darkly for designing the webpage. Bootstrap darkly will be included in the source files.

<link rel="stylesheet" href="bootstrap-darkly.min.css">

<div class="container">
    <div class="row">
        <div class="offset-md-4 col-md-4">
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Select videos
                    <input type="file" name="videos[]" class="form-control" required multiple>
                </div>

                <input type="submit" name="submit" class="btn btn-primary" value="Merge">
            </form>
        </div>
    </div>
</div>

Step 3 – Merge multiple videos

The next step is to merge multiple videos selected by user. Paste the following code on top of your file including the PHP starting and closing tags:

<?php

if (isset($_POST["submit"]))
{
    $content = "";
    for ($a = 0; $a < count($_FILES["videos"]["name"]); $a++)
    {
        $content .= "file " . $_FILES["videos"]["name"][$a] . "\n";
    }
    file_put_contents("mylist.txt", $content);

    $command = "/usr/local/bin/ffmpeg -f concat -i mylist.txt -c copy output.mp4";
    system($command);
}

?>

Step 4 – Preview of selected videos

At this point, you will be able to select multiple videos and see all of them combined into one named “output.mp4” when the form submits. However, you can do ONE MORE THING….. You can display a preview of each video before submitting the form. To do this, first you have to add an “onchange” listener on input type file, which will be a javascript function that will be called when the user select the videos.

<input type="file" name="videos[]" class="form-control" required multiple onchange="onFileSelected(this);">

This will call the javascript function called “onFileSelected” and send the input type file as a parameter. Now we are going to create a function.

<div id="videos"></div>

Create this div tag where you want to show the preview of videos (may be just below input type file). Make sure to give it a unique ID.

At the bottom of file paste the following code along with script tag at the start and end:

<script>

function onFileSelected(self) {
    var videos = document.getElementById("videos");

    for (var a = 0; a < self.files.length; a++) {
        var file = self.files[a];
        var fileReader = new FileReader();

        fileReader.onload = function (event) {
            var src = event.target.result;
            var newVideo = document.createElement("video");

            newVideo.setAttribute("src", src);
            newVideo.setAttribute("controls", "controls");
            newVideo.setAttribute("width", 500);

            videos.appendChild(newVideo);
        };

        fileReader.readAsDataURL(file);
    }
}

</script>

That’s it, now you can view the preview of all videos before combining them into one. If you wanted to have the source code of this script, you can get it from the button below. Make sure you download it and let us know if you face any issue.

Since you have learned now how to merge multiple videos into one. You can also check our tutorial to split single video file into multiple parts.

[wpdm_package id=’152′]

Split video in multiple parts – PHP & FFmpeg

To split video files in 2 parts or extracting a specific part from a long video is usually done by some of the softwares available on the internet. Some operating systems provides basic editing softwares for free, for example Windows 10 has built-in video editor in their Windows Media Player. Macintosh has QuickTime player and iMovie which came along with operating system for free. If you do not have such editor you can always download from the internet and sometimes you have to pay some amount because some of them are not free. In this tutorial, we will be creating a simple PHP script that will help you to split a video and save the extracted part as a separate video.

Step 1 – Download FFmpeg

First you need to download and install FFmpeg encoder which you can download from here: Download FFmpeg. This encoder is used to edit video and audio files, you can edit MP4/FLV/MKV/3GP or MOV files. You can edit all types of audio files from this too including MP3, WAV or OGG. FFmpeg is basically a command line tool so after installation try to run the command in your terminal or command prompt:

> ffmpeg

This will make sure FFmpeg has been installed perfectly in your system. Now you can use it’s commands, you can find all documentation in it’s official website.

Step 2 – Creating layout

The design is quite simple, we will be using bootstrap darkly for designing the webpage. Bootstrap darkly will be included in the source files.

<link rel="stylesheet" href="bootstrap-darkly.min.css">

<div class="container" style="margin-top: 100px;">
    <div class="row">
	<div class="offset-md-4 col-md-4">
	    <form method="POST" enctype="multipart/form-data">
	        <div class="form-group">
	            <label>Video</label>
       	            <input type="file" name="video" class="form-control">
	        </div>

               <div class="form-group">
                   <label>Cut from</label>
                   <input type="text" name="cut_from" class="form-control" placeholder="00:00:00">
               </div>

               <div class="form-group">
                   <label>Duration</label>
                   <input type="text" name="duration" class="form-control" placeholder="00:00:00">
              </div>

              <input type="submit" name="submit" class="btn btn-primary" value="Split">

	    </form>
	</div>
    </div>
</div>

Step 3 – Split video in multiple parts

The next step is to split the file based on user input. Paste the following code on top of your file including the PHP starting and closing tags:

<?php

if (isset($_POST["submit"]))
{
    $file_name = $_FILES["video"]["tmp_name"];
    $cut_from = $_POST["cut_from"];
    $duration = $_POST["duration"];

    $command = "/usr/local/bin/ffmpeg -i " . $file_name . " -vcodec copy -ss " . $cut_from . " -t " . $duration . " output.mp4";
    system($command);
}

?>

Step 4 – Preview of selected video

At this point your script is working perfectly. One more thing you can add is to display the preview of video before performing the splitting action. So that the user can know which video he is about to split. To do this first you have to create a video tag just below input type file, so the preview of video will be displayed beneath the input field.

<video width="500" height="320" id="video" controls></video>

This will set the width and height of video. Make sure to give the unique “id” attribute and also the “controls” attribute. The id attribute will help in javascript to get the video tag and display the preview of selected video and controls attribute will display the controls in html5 video player.

Now you need to attach a javascript listener that will be called when the user selects the file. Go ahead and add an attribute on input type file tag.

onchange="onFileSelected(this);"

This will call the javascript function called “onFileSelected” and send the input type file as a parameter. Now we are going to create a function.

At the bottom of file paste the following code along with script tag at the start and end:

<script>

    function onFileSelected(self) {
        var file = self.files[0];
        var reader = new FileReader();

        reader.onload = function (event) {
            var src = event.target.result;
            var video = document.getElementById("video");
            video.setAttribute("src", src);
        };

        reader.readAsDataURL(file);
    }

</script>

Now that you have learned how to split the video file in multiple parts. You can also learn how to merge multiple videos into one. Follow this tutorial to do that.

[wpdm_package id=’150′]

Live CRUD with AJAX – PHP

By live CRUD with AJAX, we mean that you will be able to Create, Read, Update, Delete data without having to refresh the page. This tutorial does not have any dependency on jQuery, you can implement it without having to include jQuery in it. We will be using a sample database named classicmodels and it will be included in the source files below. It has multiple tables but we will be using a table named employees to perform all 4 operations.

Live CRUD with AJAX – PHP

Let’s get started:

Create

We will be creating a simple form to input all fields and a button to insert a new row in database. Be default, the browser redirects you to the action attribute of form but we will be using onsubmit event to prevent form from redirecting. And thus, we can call our javascript function to save data via AJAX.

<form method="POST" onsubmit="return doInsert(this);">
    <input name="first_name" placeholder="First name">
    <input name="last_name" placeholder="Last name">
		
    <input type="submit" value="Insert">
</form>

<script>
function doInsert(form) {
    var firstName = form.first_name.value;
    var lastName = form.last_name.value;
		
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "Http.php", true);
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200)
            alert(this.responseText);
    };

    ajax.send("first_name=" + firstName + "&last_name=" + lastName + "&do_insert=1");
    return false;
}
</script>

Http.php

This file will be responsible for serving all 4 operations. We will be creating a database connection and a separate block for each request. Simple !

<?php

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

if (isset($_POST["do_insert"]))
{
    $first_name = $_POST["first_name"];
    $last_name = $_POST["last_name"];
	
    $sql = "INSERT INTO `employees`(`lastName`, `firstName`) VALUES ('$last_name', '$first_name')";
    mysqli_query($connection, $sql);

    echo "Record has been inserted successfully.";
    exit();
}

Read

Display data in tabular form requires a table with unique ID to tbody tag.

<table>
    <thead>
        <tr>
	    <th>First Name</th>
	    <th>Last Name</th>
	</tr>
    </thead>

    <tbody id="data"></tbody>
</table>

<script>
    function getData() {
	var ajax = new XMLHttpRequest();
	ajax.open("GET", "Http.php?view_all=1", true);
	ajax.send();
		
	ajax.onreadystatechange = function () {
	    if (this.readyState == 4 && this.status == 200) {
		var data = JSON.parse(this.responseText);
		var html = "";

		for (var a = 0; a < data.length; a++) {
		    html += "<tr>";
			html += "<td>" + data[a].firstName + "</td>";
			html += "<td>" + data[a].lastName + "</td>";
		    html += "</tr>";
		}
				
	        document.getElementById("data").innerHTML = html;
	    }
	};
    }

    getData();
</script>

Http.php

There are no parameters in the AJAX request so for the sake of simplicity, in this file we will just be fetching all records from database. Paste the following code right below INSERT block done in previous step in Http.php:

if (isset($_GET["view_all"]))
{
    $sql = "SELECT * FROM employees";
    $result = mysqli_query($connection, $sql);

    $data = array();
    while ($row = mysqli_fetch_object($result))
	    array_push($data, $row);

    echo json_encode($data);
    exit();
}

Delete

Removing a row from database is the simplest part of this tutorial, just enter an ID, sends an AJAX request and execute the DELETE command.

<form method="POST" onsubmit="return doDelete(this);">
    <input name="employee_id" placeholder="Employee ID">
    <input type="submit" value="Delete">
</form>

<script>
    function doDelete(form) {
        var employeeID = form.employee_id.value;

        var ajax = new XMLHttpRequest();
        ajax.open("POST", "Http.php", true);
        ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

        ajax.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200)
                alert(this.responseText);
        };

        ajax.send("employee_id=" + employeeID + "&do_delete=1");
        return false;
    }
</script>

Http.php

We will be using simple DELETE query to remove a row from database. Paste the following code right below VIEW ALL block done in previous step in Http.php:

if (isset($_POST["do_delete"]))
{
    $employee_id = $_POST["employee_id"];

    $sql = "DELETE FROM employees WHERE employeeNumber = '" . $employee_id . "'";
    mysqli_query($connection, $sql);

    echo "Record has been deleted";
    exit();
}

Update (a)

Updating the data would require 2 forms, 1 to get data of record you want to update, and 2nd to actually update the data in database. First we are going to get the record which needs to be updated:

<form method="POST" onsubmit="return getData(this);">
    <input name="employee_id" placeholder="Employee ID">
    <input type="submit" value="Search">
</form>

<script>
function getData(form) {
    var employeeID = form.employee_id.value;

    var ajax = new XMLHttpRequest();
    ajax.open("POST", "Http.php", true);
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            var form = document.getElementById("form-update");

            /* Show data in 2nd form */
            form.first_name.value = data.firstName;
            form.last_name.value = data.lastName;
            form.employee_id.value = employeeID;

            form.style.display = "";
        }
    };

    ajax.send("employee_id=" + employeeID + "&get_data=1");
    return false;
}
</script>

Http.php

This query will be almost same as for VIEW ALL function. Paste the following code right below DELETE block done in previous step in Http.php:

if (isset($_POST["get_data"]))
{
    $employee_id = $_POST["employee_id"];

    $sql = "SELECT * FROM employees WHERE employeeNumber = '" . $employee_id . "'";
    $result = mysqli_query($connection, $sql);
    $row = mysqli_fetch_object($result);

    echo json_encode($row);
    exit();
}

Update (b)

In this step, we will actually be updating the record in database. This step is almost similar to the INSERT section.

<form method="POST" onsubmit="return doUpdate(this);" id="form-update" style="display: none;">
    <input type="hidden" name="employee_id">
    <input name="first_name" placeholder="First name">
    <input name="last_name" placeholder="Last name">
    <input type="submit" value="Update">
</form>

<script>
function doUpdate(form) {
    var firstName = form.first_name.value;
    var lastName = form.last_name.value;
    var employeeID = form.employee_id.value;

    var ajax = new XMLHttpRequest();
    ajax.open("POST", "Http.php", true);
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200)
            alert(this.responseText);
    };

    ajax.send("first_name=" + firstName + "&last_name=" + lastName + "&employee_id=" + employeeID + "&do_update=1");

    return false;
}
</script>

Http.php

Paste the following code right below GET DATA block done in previous step in Http.php:

if (isset($_POST["do_update"]))
{
    $first_name = $_POST["first_name"];
    $last_name = $_POST["last_name"];
    $employee_id = $_POST["employee_id"];

    $sql = "UPDATE `employees` SET `lastName` = '$last_name', `firstName` = '$first_name' WHERE employeeNumber = '" . $employee_id . "'";
    mysqli_query($connection, $sql);

    echo "Record has been updated successfully.";
    exit();
}

That’s how you can implement a complete live CRUD operation with AJAX, PHP and MySQL. If you want to get more advanced. You can check our tutorial on doing a CRUD operation in Vue JS.

[wpdm_package id=’146′]

Run cron jobs on localhost

In this tutorial, you will be learning to create and run cron jobs on localhost. You will need XAMPP or WAMP and this tutorial is for Windows OS only. We will be creating a cron job that will insert a new row in database once a day. We will be using Windows Task Scheduler to tell which file to execute as a cron jobs.

Insert row in database

Create a simple file named index.php and write the PHP code to insert a new row every time that file executes. We have created a sample database called my_db and it has only 1 table called my_table and that table has only 1 column called current_date.

<?php

// Connecting with database
$connection = mysqli_connect("localhost", "root", "", "my_db");

// Getting current date
$date_time = date("Y-m-d");

// Inserting in database
mysqli_query($connection, "INSERT INTO my_table(current_date) VALUES('$date_time')");

Creating script.bat file for windows Task Scehduler

Script.bat is the file that will tell the windows task scheduler which file to execute as a cron job. In this file, you have to tell the path to your php.exe file which is located in your XAMPP or WAMP “php” folder and the path to your index.php file. Create a simple file named script.bat and paste the following code in it:

"path_to_php.exe" -f "path_to_index.php"

Creating a VBS file

A VBS file should be created that will tell the path of script.bat file. Create a new file named shell.vbs and paste the following code in it:

'Starts a new windows shell process (command line).
Set WinScriptHost = CreateObject("WScript.Shell")

'Runs a command and sets the character set for the text string, "script.bat"
WinScriptHost.Run Chr(34) & "script.bat" & Chr(34), 0

'Tells the shell not to display the window.
Set WinScriptHost = Nothing

Setting up Task Scheduler

You can follow the video below to setup the task scheduler in your windows:

That’s how you can run cron jobs on your localhost in windows operating system. If you face any problem in following this, kindly do let us know.

Follow more PHP tutorials.

[wpdm_package id=’144′]

Crop and save image – PHP

You can crop the image before uploading and save it on your server using PHP. Cropping an image would require a jQuery library called cropper. You can download the cropper library from the link below:

Download cropper library

Go ahead and download this library. You will also need jQuery for this. All files have also been included in the source files below.

Including library files

After downloading and placing the files in your project, you will be need to include 3 files. jQuery, cropper.css and cropper.js. You can find those files in the source files below:

index.php

<script src="jquery-3.3.1.min.js"></script>
<script src="cropper.js"></script>
<link rel="stylesheet" type="text/css" href="cropper.css">

<!-- Image needs to be cropped, should be displayed in an <img> tag -->
<img src="adnan-afzal.jpg" style="width: 200px;" id="image">

<!-- Initiating the library and disabling the zoom from mouse wheel and from laptop mousepad -->
<script>
    $(function () {
        $("#image").cropper({
            zoomable: false
        });
    });
</script>

<!-- If you want to remove the background and make it transparent, you can apply the following styles -->
<style>
    .cropper-crop {
        display: none;
    }
    .cropper-bg {
        background: none;
    }
</style>

At this point, you will be able to crop the selected image in <img> tag. Next step is to save the cropped area from image.

Saving image cropped area

First you have to create a simple button, upon click will send an AJAX request with cropped area:

<!-- A button when clicked will save the cropped area -->
<button type="button" onclick="crop();">
    Crop
</button>

<script>
function crop() {
    // Blob is a textual form of an image which will be obtained from <img> tag
    $("#image").cropper("getCroppedCanvas").toBlob(function (blob) {

        // FormData is a built-in javascript object
        var formData = new FormData();
        formData.append("croppedImage", blob);

        $.ajax({
            url: "upload.php", // name of the file which we will be creating soon
            method: "POST",
            data: formData,
            processData: false, // necessary for sending image data
            contentType: false, // necessary for sending image data
            success: function (response) {
                alert(response);
            }, error: function (xhr, status, error) {
                console.log(status, error);
            }
        });
    });
}
</script>

Now, we just have to create a new file named upload.php and paste the following code in it. The code is pretty simple, we can storing the image sent from AJAX using the built-in PHP function called move_uploaded_file():

upload.php

<?php

move_uploaded_file($_FILES["croppedImage"]["tmp_name"], "Cropped image.jpg");
echo "Image has been uploaded";

That’s it, go on and try cropping an image and hit the “Crop” button. Your cropped area will be saved as “Cropped image.jpg”.

[wpdm_package id=’142′]

Dynamic Pagination – PHP

Dynamic pagination is one of the most amazing way to optimize your page load if you have a lot of record in your database. You can see it in a tech giant Google, when you search for something, you will see a list of page numbers at the bottom of page. We will be using a sample database called classicmodels and we are assuming to display 5 records in one page.

Creating a layout

Our layout should be super simple, a simple bootstrap table and an unordered list for page number list:

<table class="table">
    <tr>
        <th>Employee number</th>
        <th>First name</th>
        <th>Last name</th>
        <th>Email</th>
    </tr>
</table>

Displaying dynamic pagination links

To display pagination links, we have to divide total rows by the number of records we want to display in 1 page. For example, if you have 30 records in your database and you want to display 5 records in 1 page, the formula should be:

30 / 5 = 6

Thus, 6 links will be displayed in an unordered list:

// Connecting with database
$connection = mysqli_connect("localhost", "root", "", "classicmodels");
// How many records will be displayed in one page
$record_per_page = 5;
// Getting total number of records
$sql = "SELECT COUNT(*) AS total FROM employees";
$result = mysqli_query($connection, $sql);
$total = mysqli_fetch_object($result)->total;
// Calculating number of pagination links required
$pages = ceil($total / $record_per_page);

Then we can simply loop till $pages variable and display the list items:

<ul class="pagination">
    <?php for ($a = 1; $a <= $pages; $a++): ?>
        <li class="<?php echo $a == $page_number ? 'active' : ''; ?>">
            <a href="?page=<?php echo $a; ?>">
                <?php echo $a; ?>
            </a>
        </li>
    <?php endfor; ?>
</ul>

At this point, if you run the file you will only see pagination links. On clicking you will see $page variable in the URL. We will be using this to display records as per that page.

Displaying records based on page number

Before the <table> tag, you need to check if there is $page variable in the URL. If not, then the variable should have value 1, by default. To append that variable in MySQL query, we need to subtract 1 from it as the index starts from 0. Then we will multiply it with 5 (number of records in 1 page). So your basic formula should be:

($page_number – 1) * 5

So if you are on page 3, then putting the values you will get:

(3 – 1) * 5 = 10

Thus, it will get records from 10 to 15. Below is the code for it:

$page_number = isset($_GET["page"]) ? $_GET["page"] : 1;
$start_from = ($page_number - 1) * $record_per_page;
$sql = "SELECT * FROM employees LIMIT " . $start_from . ", " . $record_per_page;
$result = mysqli_query($connection, $sql);

And to display it in <table> you can do:

<?php while ($row = mysqli_fetch_object($result)): ?>
    <tr>
        <td><?php echo $row->employeeNumber; ?></td>
        <td><?php echo $row->firstName; ?></td>
        <td><?php echo $row->lastName; ?></td>
        <td><?php echo $row->email; ?></td>
    </tr>
<?php endwhile; ?>

That’s it. You can also learn dynamic pagination in Node JS and Mongo DB from here.

[wpdm_package id=’140′]