Shopping cart – PHP | Cookies

In this tutorial, we will teach you how you can create a shopping cart in PHP using cookies.

  • We will be using Bootstrap for design.
  • We have created a link which when clicked will open the cart page where all items added in cart will be displayed.
  • First we will display all products from database, so we have created a connection with database, fetch all products using PHP and MySQL.
  • To check if item is already added in cart, we have to get all the cart items. We are storing shopping cart in cookies, and we can only store string values in cookies. So we will return the current cart if exists, if not exists then we will start with an empty array.
  • Then we will loop (while loop) through all the products from database, and inside that loop we will run another loop (foreach loop) to check if the item already exists in cart. Boolean variable $flag will tell if the item already exists in cart or not.
  • We are displaying product name and price from database. You might also have product image as well.
  • Then we will create a form for deleting the product from cart if the item already exists. It will have product unique ID (productCode in our case) as hidden field. Othewise, we will create a form to add product in cart. It will also have product ID along with quantity, by default 1 quantity.

index.php

<!-- include bootstrap -->
<link rel="stylesheet" href="bootstrap.css">
<script src="jquery-3.3.1.min.js"></script>
<script src="bootstrap.js"></script>

<div class="container" style="margin-top: 50px;">

    <!-- link to open cart page -->
    <div class="row">
        <div class="col-md-6">
            <a href="cart.php" class="btn btn-link">
                Cart
            </a>
        </div>
    </div>

    <div class="row">
        <?php
        // connect with database
        $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");
        
        // get all products
        $result = mysqli_query($conn, "SELECT * FROM products");

        // get cookie cart
        $cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
        $cart = json_decode($cart);

        // loop through all cart items
        while ($row = mysqli_fetch_object($result))
        {
            // check if product already exists in cart
            $flag = false;
            foreach ($cart as $c)
            {
                if ($c->productCode == $row->productCode)
                {
                    $flag = true;
                    break;
                }
            }
            ?>

            <div class="col-md-3" style="margin-bottom: 20px;">
                <div class="card" style="height: 200px;">
                    <div class="card-body">
                        <h5 class="card-title">
                            <?php echo $row->productName; ?>
                        </h5>
                        <p class="card-text">
                            <?php echo $row->buyPrice; ?>
                        </p>

                        <?php if ($flag) { ?>

                            <!-- show delete button if already exists -->

                            <form method="POST" action="delete-cart.php">
                                <input type="hidden" name="productCode" value="<?php echo $row->productCode; ?>">
                                <input type="submit" class="btn btn-danger" value="Delete from cart">
                            </form>

                        <?php } else { ?>

                            <!-- add to cart -->

                            <form method="POST" action="add-cart.php">
                                <input type="hidden" name="quantity" value="1">
                                <input type="hidden" name="productCode" value="<?php echo $row->productCode; ?>">
                                <input type="submit" class="btn btn-primary" value="Add to cart">
                            </form>

                        <?php } ?>

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

            <?php
        }
        ?>
    </div>
</div>

If you run the code now, you will be able to view all products from database along with button to add cart. As we havn’t added any product in cart yet so it will not display the delete button.

all-products-using-php-mysql
all-products-using-php-mysql

Time to add the products in shopping cart using PHP cookies.

add-cart.php

Create a new file named add-cart.php. In this file:

  • We will connect with database and fetch product’s data using it’s ID. Because we will storing product’s information in cart as well.
  • We are getting the current cookie array and push the new product in it along with it’s quantity.
  • Then we will save the cookie using the setcookie(name, value) function.
  • As cookies can only be saved in string, so we are converting the PHP Array into JSON string using json_encode($array) function.
  • And finally redirecting the user back to home page where all products are being displayed.
<?php

$conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");

$quantity = $_POST["quantity"];
$productCode = $_POST["productCode"];

$cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
$cart = json_decode($cart);

$result = mysqli_query($conn, "SELECT * FROM products WHERE productCode = '" . $productCode . "'");
$product = mysqli_fetch_object($result);

array_push($cart, array(
    "productCode" => $productCode,
    "quantity" => $quantity,
    "product" => $product
));

setcookie("cart", json_encode($cart));
header("Location: index.php");

?>

If you run the code now and click on “add cart” button on any product, you will see its text change to “delete from cart”.

added-in-cart-php-cookies
added-in-cart-php-cookies

If you click on delete button, you will see an error for file not found because we havn’t created that file yet, too obvious 🙂

delete-cart.php

Create a new file named delete-cart.php. In this file:

  • We are getting the product ID and all items from cart.
  • Create a new array which will have all the products except the one selected for deletion.
  • Then we will update the cookie with new array, having all the other products other than the deleted product.
  • And redirecting back to home page.
<?php

$productCode = $_POST["productCode"];

$cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
$cart = json_decode($cart);

$new_cart = array();
foreach ($cart as $c)
{
    if ($c->productCode != $productCode)
    {
        array_push($new_cart, $c);
    }
}

setcookie("cart", json_encode($new_cart));
header("Location: index.php");

?>

Now if you run the code, you will see once you click on delete button that text will be changed back to “add to cart”. That is because the product is being deleted from cart using cookies. Now we need to show all cart items on a separate page usually called “Cart” 🙂

cart.php

Create a new file named cart.php. We already have a link to this file. In this file:

  • Get all the cart items from cookies using PHP.
  • Create 2 forms, 1 to delete the product, and second to update the quantity of product.
  • We already have an implementation for deleting the product from cart.
  • In update form, we will create a quantity field which user can change. And a hidden field for product ID.
  • We are also displaying the total of all cart items by multiplying the product price by the quantity (product price * quantity = total)
<link rel="stylesheet" href="bootstrap.css">
<script src="jquery-3.3.1.min.js"></script>
<script src="bootstrap.js"></script>

<div class="container" style="margin-top: 50px;">

    <?php
    $cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
    $cart = json_decode($cart);

    $total = 0;

    foreach ($cart as $c)
    {
        $total += $c->product->buyPrice * $c->quantity;
        ?>
        <div class="row">
            <div class="col-md-12">
                <div class="card" style="height: 200px;">
                    <div class="card-body">
                        <h5 class="card-title"><?php echo $c->product->productName; ?></h5>
                        <p class="card-text"><?php echo $c->product->buyPrice * $c->quantity; ?></p>

                        <form method="POST" action="delete-cart.php" style="float: right; margin-left: 10px;">
                            <input type="hidden" name="productCode" value="<?php echo $c->productCode; ?>">
                            <button type="submit" class="btn btn-danger">
                                x
                            </button>
                        </form>

                        <form method="POST" action="update-cart.php" style="float: right;">
                            <input type="number" name="quantity" min="1" value="<?php echo $c->quantity; ?>">
                            <input type="hidden" name="productCode" value="<?php echo $c->productCode; ?>">
                            <input type="submit" class="btn btn-warning" value="Update">
                        </form>

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

        <?php
    }
    ?>

    <p>
        <?php echo $total; ?>
    </p>

</div>

If you run the code now, you will see a list of all cart items added along with update and delete button:

Shopping cart - PHP
Shopping cart – PHP

Try to change the quantity of any product and hit “update”, it will redirect you to a page where shopping cart needs to be updated.

update-cart.php

Create a new file named update-cart.php. In this file:

  • We are searching for that product using it’s ID.
  • When found, we are updating it’s quantity value with the new one.
  • And finally updating the cookie using PHP and redirecting back to home page.
<?php

$productCode = $_POST["productCode"];
$quantity = $_POST["quantity"];

$cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
$cart = json_decode($cart);

foreach ($cart as $c)
{
    if ($c->productCode == $productCode)
    {
        $c->quantity = $quantity;
    }
}

setcookie("cart", json_encode($cart));
header("Location: cart.php");

We know that you might be following this in your current working project and every project has a different scenario. So if you face any problem in following this, feel free to ask in the comments section below.

[wpdm_package id=’487′]

PHP vs Javascript – Performance test

We are going to do a performance test on getting the data from MySQL database using PHP vs getting data from MySQL database using AJAX in Javascript. We have a database named classicmodels and a table named orderDetails.

In both the cases, we are fetching data from MySQL database with the help of PHP. But in 1st case, we load the data directly via PHP. And in 2nd case, we load the data via AJAX. It is basically loading the data PHP vs Javascript.

Following is a code that will get the data from database using PHP:

<table>
    <tr>
	    <th>Order number</th>
	    <th>Product code</th>
	    <th>Quantity ordered</th>
	    <th>Price each</th>
	    <th>Order line number</th>
    </tr>
 
    <?php
        $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels") or die(mysqli_connect_error());
    
        $sql = "SELECT * FROM orderdetails";
        $result = mysqli_query($conn, $sql);

        $data = array();
        while ($row = mysqli_fetch_object($result))
        {
            ?>

            <tr>
                <td><?php echo $row->orderNumber; ?></td>
                <td><?php echo $row->productCode; ?></td>
                <td><?php echo $row->quantityOrdered; ?></td>
                <td><?php echo $row->priceEach; ?></td>
                <td><?php echo $row->orderLineNumber; ?></td>
            </tr>

            <?php
        }
    ?>
</table>

We have created a table with 5 columns. Then we are making a connection with the MySQL database. Then we are getting all the data from orderDetails table. We are using a while loop to loop through all records and mysqli_fetch_object function will return the next row in each iteration. When we use PHP to get data from the database, we get the following results in performance:

performance test php
performance test php

Now we use the same database, same table, the same number of records, and the same output. In order to get the data using Javascript, we need to create an HTML tag for the table. No need to run any PHP query, not even connection with the database. Give a unique ID to the tag where you want to display all data, in this case, we want to show the data in the table so we have given an ID to tbody tag. Then we are sending an AJAX (no jQuery needed) to test.php file and when the response is received from that file, then we display that data in tbody tag. The response sent from test.php is JSON string so we have to decode that using Javascript JSON.parse function.

index.php

<table>
    <tr>
	    <th>Order number</th>
	    <th>Product code</th>
	    <th>Quantity ordered</th>
	    <th>Price each</th>
	    <th>Order line number</th>
    </tr>
 
    <tbody id="data"></tbody>
</table>
 
<script>
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "test.php", true);
    ajax.send();
 
    ajax.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

        	console.log(this.responseText);
            var data = JSON.parse(this.responseText);
            console.log(data);
 
            var html = "";
            for(var a = 0; a < data.length; a++) {
                html += "<tr>";
                    html += "<td>" + data[a].orderNumber + "</td>";
                    html += "<td>" + data[a].productCode + "</td>";
                    html += "<td>" + data[a].quantityOrdered + "</td>";
                    html += "<td>" + data[a].priceEach + "</td>";
                    html += "<td>" + data[a].orderLineNumber + "</td>";
                html += "</tr>";
            }
            document.getElementById("data").innerHTML += html;
        }
    };
</script>

Now we need to create a file that will handle that AJAX request. This code will be almost same as we did in simple PHP, but instead of displaying all data, we are adding all data in an array and sending that array as a JSON string to AJAX response using PHP built-in json_encode() function.

test.php

<?php

	$conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels") or die(mysqli_connect_error());
	
	$sql = "SELECT * FROM orderdetails";
	$result = mysqli_query($conn, $sql);

	$data = array();
	while ($row = mysqli_fetch_object($result))
	{
		array_push($data, $row);
	}
	echo json_encode($data);
	exit();
?>

And these are the results we get when we fetch data from database using Javascript and AJAX:

performance test PHP
performance test javascript
performance test javascript

Conclusion

PerformancePHPJavascript
Page speed74%93%
Time to load page8.6 seconds5.5 seconds
Page size1.24 MB966 KB
Requests14062

[wpdm_package id=’475′]

MongoDB tutorials

Learn MongoDB basics from our easy-to-follow tutorials.

Table of content:

  1. Download and Installation.
  2. Insert and read documents.
  3. Query document.
  4. Projected fields, limit, skip, and sort.
  5. Update, increment, and delete documents.
  6. Aggregation and group by clause.
  7. Indexing.
  8. Capped collections (automatically remove previous documents).
  9. Text search.
  10. Deployment (mlab.com)

1. Download and Installation

Video tutorial:

You can download MongoDB from their official site: https://www.mongodb.com/download-center and you need to select “Community server” if you are using it for localhost or small websites. For a very large company, I would recommend “Enterprise server”. Once downloaded, extract the zip file and you will see a folder named “mongodb”. Inside this folder, you will have another folder named “bin”.

Now open your terminal in that folder, you can use the following command:

cd "path to bin folder of mongodb"

Once you are inside the folder, you can start the MongoDB server using following command:

./mongod

If that didn’t work, try simple:

mongod
mongodb start the server

Connect with MongoDB

Once your MongoDB server is started, you can open the database by opening a new command terminal. You can either open a new terminal window (window + n) or new tab (window + t).

window = cmd in Mac OS

And in terminal window or tab, run the following command (make sure the MongoDB server is running from previous command):

./mongo

If that didn’t work, try simple:

mongo
connect database – MongoDB tutorials

Now you are in your database server. Here you can enter any MongoDB command to perform specific actions. By default, MongoDB server creates some databases for administrators and configurations. You can view all databases in the MongoDB server by running the following command:

show dbs
mongodb view all databases

To create a database, you just need to use the “use” command. Use command will create a database if not exists, and open the database if already exists. For example, to create a database for users, run the following command:

use users

In all the tutorials of this MongoDB series, we will be using “users” collection.

Now if you run the command “show dbs“, you will NOT see your “users” database. This is because it will be displayed only when there is at-least one document in it.

We will know more about documents and collections and how to add them in the next tutorial.

Count words as user type – Textarea & Javascript

Demo

In this tutorial, we are going to teach you how you can count the number of words in textarea as user type in it. The first thing you need to do is to attach an onkeyup listener to your textarea tag. This function will be called whenever user pressed the key. Specifically, when the user’s finger is moving upwards after pressing the key, then this event is called. In this function, we are passing a parameter this means current node, which is textarea tag.

<textarea onkeyup="countWords(this);"></textarea>
<span id="words-counter"></span>

Then we created a span tag, you can create a div or paragraph as well. Give that span tag a unique ID so it can be accessible in Javascript. We will be displaying the number of words in this span tag.

Then we create this function in Javascript, first, we are getting the current text inside textarea field using the value attribute. Then we are applying a regular expression which states that:

Count the number of words
separated by spaces.

This will return an array, we simply have to calculate the length of that array. We are using a ternary operator to get value as 0 if the spaces array is null. Finally, we are displaying that length in the span tag using plain Javascript.

function countWords(self) {
	var spaces = self.value.match(/\S+/g);
	var words = spaces ? spaces.length : 0;

	document.getElementById("words-counter").innerHTML = words + " words";
}

That’s how you can count the number of words as user type in an input field using plain HTML and Javascript.Specifically in a <textarea> tag.

Shuffle an array of objects – Javascript

To shuffle an array of objects or single values in Javascript, use the following function:

for (var a = 0; a < data.length; a++) {
	var x = data[a];
	var y = Math.floor(Math.random() * (a + 1));
	data[a] = data[y];
	data[y] = x;
}

First, we are looping through all array elements. data is our array of objects. First, we are saving the current array element in a separate variable named x. Then we are generating a random number. Math.random() will return a random number between 0.0 and 0.9. As our loop start from 0, so we are multiplying that random number by loop iteration number + 1. Since the number will be in floating points, so we can convert that into an integer by calling Math.floor() function. The floor function will round the number downwards and return it as an integer. That is now the index of the random element in the array.

Then we are replacing the current array element with this random array element. And finally, replace this random array element with the current element of loop.

This is the simplest way to shuffle an array of objects using vanilla Javascript. For more Javascript tutorials, please follow here.

Confirmation dialog before deleting data – Javascript, PHP

In this tutorial, we are going to teach you how you can show a confirmation dialog before deleting any data using Javascript. Suppose you are displaying a lot of data in tabular form in the admin panel, and you have a delete button at the end of each row. Now when someone clicks on it, you may be submitting a form with POST request or redirecting to a page where that data will be deleted. But what if someone accidentally clicks on any row, or clicks the wrong row? Then that row will be deleted from the database.

Alternative

One alternative thing you can do is to put the deleted data in the trash. That will add extra work on the developer side as well as on the user side. Because you have to create a table where trashed data will be stored, then create another page on the admin panel to display trashed data and also the ability to delete or restore the trashed data. You can see that there are 6 or 7 more functions that you have to write. Moreover, there will be extra work for users too, they also have to delete the trashed data regularly.

A simple approach

A simple approach displays a confirmation dialog when the delete button is clicked. Show simple 2 buttons, “Cancel”, “Delete”. When the delete button is clicked from confirmation dialog, then send the request to delete that data from the database. You may encounter yourself in 2 minor problems in this approach. First is “how can I display a confirmation dialog ?”, you can either display javascript native function confirm() but it may not look good with your website design.

People want a more personal look, whenever you are displaying a dialog box, whether it is alert dialog or confirmation dialog, make sure that it goes with the look and feel of your website design. Or you can use external libraries like Sweetalert, so you have to download that library, include in your project, and use their functions. But sometimes you do not have your project flooded with external libraries. You may ask yourself “why to include an external library when I can do it in my design framework ?”

As we know that today almost every website is using Bootstrap and your project will also be using a large portion of the Bootstrap framework. So we are going to use Bootstrap to display a confirmation dialog. In Bootstrap, they are called “modal”.

Bootstrap modal

Bootstrap modal can be created by creating a <div> tag and give it a unique ID, also a class named “modal”. There will be 2 inner nested divs, one with class “modal-dialog” and second having class “modal-content”. Modal content div will have 3 sections:

  1. modal-header
  2. modal-body
  3. modal-footer

What we are going to do is to show heading in modal-header div, and create a form in modal-body div, in this form we will create a hidden input field which will be the unique ID of row which needs to be deleted from database. Set the form action attribute to the page where you will handle to perform the delete action. In modal-footer, we will simply create a submit button which will be linked with that form using form attribute. Make sure the form attribute on submit button will be same as form id attribute.

<div id="myModal" class="modal">
	<div class="modal-dialog">
		<div class="modal-content">
			
			<div class="modal-header">
				<h4 class="modal-title">Delete User</h4>
				<button type="button" class="close" data-dismiss="modal">×</button>
			</div>

			<div class="modal-body">
				<p>Are you sure you want to delete this user ?</p>
				<form method="POST" action="delete-user.php" id="form-delete-user">
					<input type="hidden" name="id">
				</form>
			</div>

			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				<button type="submit" form="form-delete-user" class="btn btn-danger">Delete</button>
			</div>

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

Confirmation dialog – Javascript

Now create a delete button (or change if you already have one) such that it has an attribute data-id and its value must be the unique ID of that row. Attach an onclick listener which will be called whenever that button is clicked. In this event, we are calling a function named confirmDelete. You can create this delete button inside your table row where you are displaying all data from the database (typically in while() loop).

<button type="button" class="btn btn-danger" data-id="<?php echo $row->id; ?>" onclick="confirmDelete(this);">Delete</button>

Now when the button is clicked, we want to set the value of the hidden input field inside the bootstrap modal form to the id of the selected row. Then we will show the confirmation modal. Create the following function in <script> tag:

function confirmDelete(self) {
	var id = self.getAttribute("data-id");

	document.getElementById("form-delete-user").id.value = id;
	$("#myModal").modal("show");
}

Make sure you have given a name attribute to the hidden input field. It will help you to set the value using Javascript before displaying the confirmation dialog. Also, the name attribute is used at the server-side to get the values. Now you will be asked for confirmation before deleting any data from the database WITHOUT USING ANY EXTERNAL LIBRARY other than Bootstrap.

If you are developing backend in PHP, then you can get this value using $_POST[“id”].

[wpdm_package id=’441′]

Calculate time passed since date in days, hours, minutes and seconds – Javascript, PHP

Demo

Convert time to different timezones

Today, we will learn to calculate the time passed since date in days, hours, minutes and seconds. Either you are receiving values in PHP variable from MySQL database, or you are calling an AJAX request, this tutorial will help you in both situations. We will also display the hours, minutes and seconds in leading zeroes. So you will not see time as “7:9:3” but you will see that as “07:09:03” using leading zeroes. We already uploaded 1 more tutorial on calculating the time remaining. If you want to caclulate the remaining time in future date, you can follow our tutorial on that as well:

Calculate remaining time

Calculate time passed

Basically, we are going to get the difference between future date and current date. Then we will extract the days, hours, minutes and hours from that difference. Difference will be in seconds so we have to apply some math on it. First we assume that you are already receiving the value from your MySQL database in PHP variable. We have set the PHP variable below but you can use your own database value:

<?php
	$date = "2020-06-07 23:39:00";
?>

Then we will create a <div> where we will display the time passed and a hidden input field to get the PHP variable value in Javascript.

<div id="data"></div>

<input type="hidden" id="date" value="<?php echo $date; ?>">

JS function when page loads

Then create a Javascript function which will be called once simply when the page loads. And then in a setInterval function which will be called each second, so we will display the time passed in seconds as well. We will get 2 date objects, first will be current date and second will be date in future which we are getting from PHP variable.

Get difference in timestamps

Then we will get the timestamp from both dates in milliseconds using getTime() function. Dividing that by 1000 will convert that in seconds. But we will also get the floating numbers when dividing, we can prevent the floating number by calling toFixed(0) function. Since toFixed() function returns a string which will not be helpful in getting the difference between 2 dates, so we have to convert that in double or float. We can do that by calling Math.abs() function, it will return the absolute value. Then we subtract the future timestamp from current timestamp and save that in a variable diff as difference.

This diff variable is also in seconds, now we have to convert that value into days, hours, minutes and seconds. We know that there are 86400 seconds in each day, so dividing the difference by 86400 will return the number of days remaining. And since dividing also cause floating number, so we can prevent that by calling Math.floor() function. It will round the value to the previous number.

For example, if the value is 23.7 then it will return as 23. Time to get the remaining hours, we know that there are 3600 seconds in each hour, so we will divide that difference by 3600, round the value to floor. And since there are 24 hours in each day, so we have to take the modulus by 24. Taking modulus will divide the value and return the remainder.

Get difference in minutes

To get the minutes, we know that there are 60 seconds in each minute and 60 minutes in each hour. So we divide the difference by 60, round the value by floor, then take the modulus by 60. That will return the number of minutes passed since date. To get the seconds, is the simplest among all.

We know the limit for seconds is 60, so we simply take the modulus of difference by 60 and it will return the seconds. If you want to show the leading zeros i.e. zeroes on left if value is less than 10, then you can also put a condition on days, hours, minutes and seconds. Check if the value is less than 10, then prepend the “0” with value. And finally display that in our <div id=”data”></div>

Make sure to call the function in setInterval to update the value each second.

<script>
	function func() {
		var dateValue = document.getElementById("date").value;

		var currentDate = Math.abs((new Date().getTime() / 1000).toFixed(0));
		var futureDate = Math.abs((new Date(dateValue).getTime() / 1000).toFixed(0));

		var diff = currentDate - futureDate;

		var days = Math.floor(diff / 86400);
		var hours = Math.floor(diff / 3600) % 24;
		var minutes = Math.floor(diff / 60) % 60;
		var seconds = diff % 60;

		if (days < 10) {
			days = "0" + days;
		}

		if (hours < 10) {
			hours = "0" + hours;
		}

		if (minutes < 10) {
			minutes = "0" + minutes;
		}

		if (seconds < 10) {
			seconds = "0" + seconds;
		}

		document.getElementById("data").innerHTML = days + " days, " + hours + ":" + minutes + ":" + seconds;
	}

	func();
	setInterval(func, 1000);
</script>

[wpdm_package id=’432′]

Calculate remaining time in days, hours, minutes and seconds – Javascript, PHP

Demo

Convert time to different timezones

Today, we will learn to calculate remaining time till future date in days, hours, minutes and seconds. Either you are receiving values in PHP variable from MySQL database, or you are calling an AJAX request, this tutorial will help you in both situations. We will also display the hours, minutes and seconds in leading zeroes.

So you will not see time as “7:9:3” but you will see that as “07:09:03” using leading zeroes. We already uploaded 1 more tutorial on creating a countdown timer using libraries. If you are comfortable to use third party libraries in your project, you can follow our tutorial on that as well.

Using third party library

Basically, we are going to get the difference between current date and the date in future. Then we will extract the days, hours, minutes and hours from that difference. Difference will be in seconds so we have to apply some math on it. First we assume that you are already receiving the value from your MySQL database in PHP variable. We have set the PHP variable below but you can use your own database value:

<?php
	$date = "2020-06-07 23:39:00";
?>

Then we will create a <div> where we will display the remaining time and a hidden input field to get the PHP variable value in Javascript.

<div id="data"></div>

<input type="hidden" id="date" value="<?php echo $date; ?>">

JS function when page loads

Then create a Javascript function which will be called once simply when the page loads. And then in a setInterval function which will be called each second, so we will display the remaining time in seconds as well. We will get 2 date objects, first will be current date and second will be date in future which we are getting from PHP variable.

Then we will get the timestamp from both dates in milliseconds using getTime() function. Dividing that by 1000 will convert that in seconds. But we will also get the floating numbers when dividing, we can prevent the floating number by calling toFixed(0) function.

Convert string to double – Javascript

Since toFixed() function returns a string which will not be helpful in getting the difference between 2 dates, so we have to convert that in double or float. We can do that by calling Math.abs() function, it will return the absolute value. Then we subtract the current timestamp from future timestamp and save that in a variable diff as difference.

This diff variable is also in seconds, now we have to convert that value into days, hours, minutes and seconds. We know that there are 86400 seconds in each day, so dividing the difference by 86400 will return the number of days remaining. And since dividing also cause floating number, so we can prevent that by calling Math.floor() function. It will round the value to the previous number.

For example, if the value is 23.7 then it will return as 23. Time to get the remaining hours, we know that there are 3600 seconds in each hour, so we will divide that difference by 3600, round the value to floor. And since there are 24 hours in each day, so we have to take the modulus by 24. Taking modulus will divide the value and return the remainder.

Get seconds from timestamp – Javascript

To get the minutes, we know that there are 60 seconds in each minute and 60 minutes in each hour. So we divide the difference by 60, round the value by floor, then take the modulus by 60. That will return the number of minutes remaining till date. To get the seconds, is the simplest among all.

We know the limit for seconds is 60, so we simply take the modulus of difference by 60 and it will return the seconds. If you want to show the leading zeros i.e. zeroes on left if value is less than 10, then you can also put a condition on days, hours, minutes and seconds. Check if the value is less than 10, then prepend the “0” with value. And finally display that in our <div id=”data”></div>

Make sure to call the function in setInterval to update the value each second. Following function will calculate the remaining time.

<script>
    function func() {
        var dateValue = document.getElementById("date").value;

        var date = Math.abs((new Date().getTime() / 1000).toFixed(0));
        var date2 = Math.abs((new Date(dateValue).getTime() / 1000).toFixed(0));

        var diff = date2 - date;

        var days = Math.floor(diff / 86400);
        var hours = Math.floor(diff / 3600) % 24;
        var minutes = Math.floor(diff / 60) % 60;
        var seconds = diff % 60;

        var daysStr = days;
        if (days < 10) {
            daysStr = "0" + days;
        }
 
        var hoursStr = hours;
        if (hours < 10) {
            hoursStr = "0" + hours;
        }
 
        var minutesStr = minutes;
        if (minutes < 10) {
            minutesStr = "0" + minutes;
        }
 
        var secondsStr = seconds;
        if (seconds < 10) {
            secondsStr = "0" + seconds;
        }

        if (days < 0 && hours < 0 && minutes < 0 && seconds < 0) {
            daysStr = "00";
            hoursStr = "00";
            minutesStr = "00";
            secondsStr = "00";

            console.log("close");
            if (typeof interval !== "undefined") {
                clearInterval(interval);
            }
        }

        document.getElementById("data").innerHTML = daysStr + " days, " + hoursStr + ":" + minutesStr + ":" + secondsStr;
    }

    func();
    var interval = setInterval(func, 1000);
</script>

That’s how you can calculate the remaining time till date in Javascript.

[wpdm_package id=’421′]

Hashed password change feature – Core PHP

In this article, we will teach you how you can change the hashed password of a user in PHP.

Before you proceed, make sure you have PHP version 5 or greater than 5 till 5.5.0 (PHP 5 >= 5.5.0) or PHP 7. You can check your server’s PHP version by creating a new PHP file and write the following code in it:

<?php
	phpinfo();
?>

This tutorial uses PHP password_hash and password_verify functions that allows you to save passwords in MySQL database as hashed strings, so even if your database gets hacked or someone tries to read it, he will still not be able to find the actual passwords of users. For the sake of simplicity, we are going to use a sample table named “users” in MySQL database and it will have just 4 columns:

  1. ID (int, auto increment primary key)
  2. name (text)
  3. email (text)
  4. password (text)

Create an HTML form

Our form will contain 3 fields:

  1. Current password: to check if user has entered its current password correctly.
  2. New password
  3. Confirm password

Paste the following code in page where you want to allow user to change their password (make sure to change the form action attribute to your desired filename):

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

<div class="container" style="margin-top: 50px;">
	<div class="row">
		<div class="col-md-12">
			<form method="POST" action="index.php">
				<div class="form-group">
					<label>Current password</label>
					<input type="password" class="form-control" name="current_password" placeholder="Current password">
				</div>

				<div class="form-group">
					<label>New password</label>
					<input type="password" class="form-control" name="new_password" placeholder="New password">
				</div>

				<div class="form-group">
					<label>Confirm password</label>
					<input type="password" class="form-control" name="confirm_password" placeholder="Confirm password">
				</div>

				<p>
					<input type="submit" class="btn btn-primary" name="change_password" value="Change password">
				</p>
			</form>
		</div>
	</div>
</div>

Handle PHP request

When you submit the form above, it will send the data to “index.php” page. If you have written any other filename in “action” attribute, paste the following code in that PHP file:

<?php

	// Connect with database
	$conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");
	// Set user ID, you must be getting it from $_SESSION
	$user_id = 1;

	// This will be called once form is submitted
	if (isset($_POST["change_password"]))
	{
		// Get all input fields
		$current_password = $_POST["current_password"];
		$new_password = $_POST["new_password"];
		$confirm_password = $_POST["confirm_password"];

		// Check if current password is correct
		$sql = "SELECT * FROM users WHERE id = '" . $user_id . "'";
		$result = mysqli_query($conn, $sql);
		$row = mysqli_fetch_object($result);
		
		if (password_verify($current_password, $row->password))
		{
			// Check if password is same
			if ($new_password == $confirm_password)
			{
				// Change password
				$sql = "UPDATE users SET password = '" . password_hash($new_password, PASSWORD_DEFAULT) . "' WHERE id = '" . $user_id . "'";
				mysqli_query($conn, $sql);

				echo "<div class='alert alert-success'>Password has been changed.</div>";
			}
			else
			{
				echo "<div class='alert alert-danger'>Password does not match.</div>";
			}
		}
		else
		{
			echo "<div class='alert alert-danger'>Password is not correct.</div>";
		}
	}
?>

That’s how you can change the hashed password of a user in PHP and MySQL.

Learn how to Password protect ZIP files in Mac OS X from here.

[wpdm_package id=’254′]