UIDatePicker timezone fix – Swift iOS

UiDatePicker in Swift has some timezone issues, so we will teach you how you can fix it.

Convert time to different timezones

If you are working on UIDatePicker in your Swift project, you might come across a problem that when fetching the value from UIDatePicker it usually returns the value by mapping with your timezone. But we want to have the actual value from the date picker as it is (without having timezone mapping).

UIDatePicker timezone fix

You can use the following function to get the actual value selected from date picker:

datepicker.date.description(with: .current)

Assuming datepicker is your outlet for type UIDatePicker. You can also prevent the user from selecting previous dates by writing the following line at the end of your viewDidLoad() function:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    
    datepicker.minimumDate = Date()
}

Video tutorial:

Easy way to save the class object in user defaults – Swift iOS

When it comes to saving the class object in user defaults, there is a hard way to do using NSKeyedArchiver class. But there is an easy to do using JSONEncoder and JSONDecoder classes. In this tutorial, we will teach you how you can:

  1. Save the class object in defaults using Swift by encoding in JSON.
  2. Get a class object from defaults by decoding from JSON.
  3. Remove the class object from defaults.

First, create a model class in Swift which will be the class that needs to be stored in user defaults.

User.swift

import Foundation

class User: Codable {
    public var id: Int = 0
    public var name: String = ""
}

Make sure it is a type of Codable protocol, this will help to convert the class into JSON. Set the default values to all data members, integers to 0, and strings to empty string. Then we will create a file which will have all the functions to save, retrieve, and remove the class object value from user defaults, we name that class LocalStorageManager.

LocalStorageManager.swift

import Foundation

class LocalStorageManager {
    
    public func saveUser(user: User) {
        do {
            
            let jsonEncoder = JSONEncoder()
            let jsonData = try jsonEncoder.encode(user)
            let json = String(data: jsonData, encoding: .utf8) ?? "{}"
            
            let defaults: UserDefaults = UserDefaults.standard
            defaults.set(json, forKey: "user")
            defaults.synchronize()
            
        } catch {
            print(error.localizedDescription)
        }
    }
    
    public func getUser() -> User {
        do {
            if (UserDefaults.standard.object(forKey: "user") == nil) {
                return User()
            } else {
                let json = UserDefaults.standard.string(forKey: "user") ?? "{}"
                
                let jsonDecoder = JSONDecoder()
                guard let jsonData = json.data(using: .utf8) else {
                    return User()
                }
                
                let user: User = try jsonDecoder.decode(User.self, from: jsonData)
                return user
            }
        } catch {
            print(error.localizedDescription)
        }
        return User()
    }
    
    public func removeUser() {
        let defaults: UserDefaults = UserDefaults.standard
        defaults.removeObject(forKey: "user")
        defaults.synchronize()
    }
}
  1. Create a global data member that will be the key used to identify the object in user defaults.
  2. saveUser function will receive the User class instance as a parameter, convert that as JSON string and save in defaults.
  3. getUser function will return the user class instance by decoding from the JSON string. Here, we will handle all the validations that might be useful for decoding the JSON data.
  4. removeUser function is used to delete the user class instance from defaults.

To use this, we are going to simply call these functions from our main view controller file.

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let user: User = User()
        user.id = 565
        user.name = "Adnan"
        
        LocalStorageManager().saveUser(user: user)
        
        let cacheUser: User = LocalStorageManager().getUser() 
        print(cacheUser)
        
        LocalStorageManager().removeUser()
        
        let cacheUserAgain: User = LocalStorageManager().getUser() 
        print(cacheUserAgain)
    }
}
  1. First, we are creating an instance of user class and set the values.
  2. Then we are saving in defaults.
  3. After that, we are retrieving the saved user class object and printing it out for debugging.
  4. Finally, we are removing it from defaults and printing it out.

Learn how to do a CRUD operation using local storage in Swift UI

Local storage Swift UI – CRUD

How to export and download CSV in Node JS

Learn how to export and download CSV file in Node JS.

Video tutorial:

First, we create a folder and open the command prompt or terminal in it using the following command:

cd "path of folder"

Then you can initialize the NPM by running the following command:

npm init

Then you can install the required modules:

npm install express http fs fast-csv

We will be using express as the main module for all types of requests and responses. HTTP for starting the server, fs stands for File System, and fast-csv to create CSV files. We have created a file named “server.js”. So you can start the server by running the following command in your terminal:

nodemon server.js
# or node server.js

Create a folder named “public” in root of your Node JS folder, here we will save the CSV file. Now your “server.js” file will have the following content:

var express = require("express");
var app = express();
var http = require("http").createServer(app);
var fileSystem = require("fs");
var fastcsv = require("fast-csv");

app.use("/public", express.static(__dirname + "/public"));

http.listen(3000, function () {
    console.log("Connected");

    app.get("/exportData", function (request, result) {

        var data = [{
            "id": 1,
            "name": "Adnan",
            "age": 29
        }, {
            "id": 2,
            "name": "Ali",
            "age": 31
        }, {
            "id": 3,
            "name": "Ahmad",
            "age": 33
        }];

        var ws = fileSystem.createWriteStream("public/data.csv");
        fastcsv
            .write(data, { headers: true })
            .on("finish", function() {

                result.send("<a href='/public/data.csv' download='data.csv' id='download-link'></a><script>document.getElementById('download-link').click();</script>");
            })
            .pipe(ws);
    });
});
  1. We are first creating instances of all modules.
  2. Then we are telling the server that we will be saving files in the “public” folder.
  3. After that, we are starting the server at port 3000.
  4. Then we are creating a GET route which when accessed will create a CSV file and download it in the user’s browser.
  5. Now, we are creating an array which will be the data of CSV file. You can replace that with your own array.
  6. Then we are creating a write stream, and in that, we are sending the path of CSV file. In our case, it is in the “public” folder and named “data.csv”.
  7. Write the data array using a fast-csv module. When the writing finished, simply create an anchor tag and add an attribute “download“. Set the href to the path of file. And fire a click event using Javascript.
  8. We are using pipe() function that will add the write stream in fast-csv queue.

Explore our more tutorials and projects developed in Node JS.

[wpdm_package id=’556′]

Social Networking Site in Node JS and Mongo DB

The social networking site is a project developed in Node JS, and Mongo DB. It has all the functionality that you need to build a social network for your local community.

A social networking service is an online platform that people use to build social networks or social relationships with other people who share similar personal or career interests, activities, backgrounds, or real-life connections. Social networking services vary in format and the number of features.

wikipedia

Features list:

  1. Login and registration
  2. Update Profile
  3. Posts
  4. Like, comment, and reply
  5. Share posts in timelines, pages, and groups
  6. Notifications
  7. Search
  8. Email confirmation
  9. Reset password
  10. Create friends
  11. Create pages
  12. Create groups
  13. Realtime chat
  14. See people who viewed your profile
  15. Edit and delete the post
  16. Load more button
  17. Send images and videos in the chat
  18. See people who liked and shared your post
  19. Encryption on chat messages
  20. Ban & delete user
  21. Filter bad/abusive words
  22. Adult image validation
  23. Ban post
  24. Create events
  25. Embed YouTube videos in the post
  26. Customer support
  27. Advertisement (boost post)
  28. Emoji comments
  29. Like, dislike, comment on stories
  30. People nearby
  31. Group chat

Demo

Requirements:

Introduction

The social networking site is a project developed in Node JS and Mongo DB. It has all the functionality that you need to build a social network for your local community. Node JS is becoming a rising programming language for backend servers, it is fast and easy to learn. If you know Javascript, you already know Node JS.

On the other hand, Mongo DB is quickly becoming a standard for creating schema-less applications where the structure of your database is not important. It is widely being used in large systems to scale easily.

This project has a basic version that allows you to download the code for free and set it up in your local system. In the source files, a file named “How to install.txt” will guide you on how you can set up the project in your system. But if you are still facing a problem, you can always contact me.

Login and registration

In the basic version, you will avail of the authentication functionality that includes login and registration of the user. Passwords are encrypted before being stored in Mongo DB. The project uses JSON Web Token (JWT) for storing logged-in user’s information. JWT is used to transmit information securely between client and server. After logging in, the user will be able to update his profile picture and cover photo. Uploaded files are stored in the Node JS server using the “fs” module which stands for File System and the path of the uploaded file is stored in Mongo DB.

Post with caption, image, and video

Now come to the most important part of any social networking site, POSTS. What makes a social network great is the number of posts, so you should allow users to create posts, update their status, what they are doing, etc. The basic version can create posts using text, images, or video. Posts created by the user will only be viewed by his friends. When the post is created, the user will like the post, comment on a post, and reply to any comment. Posts can also be shared on your timeline, so you can pick any post you like and hit the “share” button, and will be displayed on your timeline as well.

When someone likes your post, comments on your post, or replies to your comment, a notification will be received on the left side of your home page. You can view a list of all notifications received and notification will be marked as read once opened.

Search

You can search people by their name, username, or email address. You can also search groups and pages as well by their name. This will create 3 tabs on the search page, first for users, second for pages, and third for groups.

Email verification

In terms of authentication, you will be able to verify the user by his email address during registration. When someone registers, an email will be sent to him with an instruction to verify their email address. Users who have not verified their emails will not be able to log in. This will help you know that the users you have on your site are actual users, not robots.

Reset password

This project also comes with the functionality to reset the password. This gives users the ability to reset their passwords if they have forgotten. When someone types his email to reset the password, the system will check if the email exists then it will send an email with a link to reset the password. When that link is opened it will confirm that it is the valid link and show the field to enter a new password.

Create friends

You can create friends by searching for people by their name, and then send them a friend request. The other person will be able to respond to that request, he can either decline or accept the request. Once accepted, you both will be able to view each other’s posts in your timeline.

Create pages

You can create pages by entering the page name, cover photo, and a short description of the page. Then you will be able to add posts to that page as well. When someone searches for that page, he will be able to view all the posts on that page. Users will be able to like the page, and once liked they will be able to view the page’s posts in their timeline as well.

Create groups

This pro version also allows you to create groups by entering the group’s name, cover photo, and a short description of the group. Once the group is created, people will be able to see it in their search results, they will send a request to join the group. Only you (admin) will be able to decline or accept the group request. Once accepted, the user will become a member of that group. Members are allowed to add posts in that group and all the other members will be able to view it in their timeline.

Realtime chat

One of the most demanding functions of a social network is chat. You make friends chat with them, in this version you will be able to have a real-time secure chat between 2 friends. We have used Sockets for real-time communication, all the messages are also being stored in Mongo DB.

People who viewed your profile

It also has a functionality where you can see a list of all people you have viewed your profile. When someone visits someone’s profile, we are storing his record in Mongo DB along with the current date and time. Then the other person will see a list of people who viewed his profile along with the time that person visited your profile recently.

Since you are creating posts, you must be able to edit and delete posts. You can edit your own created posts and you can also delete your created posts as well. Once the post is updated, it will be updated on all social networks. Although it is Mongo DB (non-relational) still manages to update the post’s document in all places. The same goes for delete, once the post is deleted, it will be deleted all over the social network.

It also has a functionality that we call “load more”. It allows you to load more posts without having to reload the page. When the social network is opened, the first 30 posts will be fetched and displayed in the browser. When the user scrolls to the bottom, a button is displayed at the bottom of the page which when clicked will fetch the next 30 posts. You can change the number of posts as you wish.

You can send images and videos in a chat with your friends. All attachments sent are being stored in the Node JS file system. You can also preview the files before sending them. Images and videos are not being compressed, so you can send high-quality images without having to worry that the system will reduce the quality of images, it will not reduce the quality of images or videos.

Share posts

You will be able to share posts in your timeline, pages you have created, and the groups you have joined.

You will be able to view a list of all people you have liked and shared your post. This is helpful for a social network where you want to know who has liked and shared your post.

This project has 15 major features that are essential for this social network:

  1. Message encryption.
  2. Customer support.
  3. Ban & delete the user.
  4. Filter bad or abusive words.
  5. Adult image validation.
  6. Ban the post.
  7. 24-hour stories
  8. Audio files
  9. Events
  10. YouTube links
  11. Advertisement (boost post)
  12. Emoji comments
  13. Like, dislike, and comments on stories
  14. People nearby
  15. Group chat

Let’s view each in detail.

1) Message encryption on chat

First, is the encryption for chat messages. When you are having a chat with your friend, instead of saving the messages in plain text, we have added the functionality to encode the message during sending and decoding the message during receiving. Thus, making the chat encrypted. The below screenshot shows how messages will be stored in the database. So only the receiver can see the message correctly.

You can check our tutorial on encryption and decryption from here.

2) Customer support

The second is customer support. If users are having a problem with any function or want to ask something, they can contact your social network’s customer support. It can be accessed from the left sidebar. Users can create a new ticket, a ticket is a problem that the user is facing. They can enter their problem, they can also attach an image or video as well to demonstrate the problem.

Created tickets will be displayed on the admin panel in a list. Admin can open any ticket from the list to respond to the corresponding user. Both admin and users can add a comment using the WYSIWYG editor, which helps them to apply styles to their comments. Users and admin can view all the comments from the other person.

The user will receive a notification that a new comment has been added to his ticket and he can respond to admin. Admin can also close the ticket when the issue is resolved. Once the ticket is closed, no-one will be able to add comments on that ticket. The user can also delete the ticket if he wants.

3) Ban & delete user

The third is banning and deleting the user. Banning means that the admin can ban any user he wants, the user’s data will remains to be stored in the database, but the user will not be able to access the system. Once banned, the user will automatically be logged out and when he tries to log in, he will be displayed an error message that he is banned. Admin can unban the user and the user will be able to login now. Admin can also delete the user from the system.

4) Filter bad/abusive words

The fourth is filtering bad words. When the user adds a new post, its content will be checked, and made sure that there are no abusive words in it. If there is any such word, then an error will be displayed and the post will not be saved. The same validation is applied when the post is edited.

5) Adult image validation

The fifth is adult image validation. When the user adds a new post and attaches an image to it, that image is checked and made sure that it must not contain any adult content. If it is an adult image, an error will be displayed and the post will not be saved. Normal images will be uploaded as they were before. The same validation is applied when the post is edited. But if you still do not like any post’s image, you can remove it from the admin panel and it will be removed from the system.

6) Ban post

The sixth is banning the post. When a user posts anything and you find it offensive, instead of deleting it, you can ban the post. So the post will not be removed from the system but it will not be visible to other users. During banning the post, you have to enter the reason to ban. This reason will be visible to the user. The user will get a notification that his post has been banned and he will also see the reason why it is banned. Admin can unban the post and the post will now be visible for everyone.

7) 24 hour stories

You will be able to upload stories that will remain for 24 hours. The stories will be displayed to you and your friends only. After 24 hours, the stories will automatically get deleted using a cron job. You can also delete the story before 24 hours as well. Users will also be able to view all the friends who have seen his story.

8) Audio files

You can upload audio files with the post. You will see the waves of the audio file as well. We are using a library called “wavesurfer” for this.

9) Events

Events are used to inform people about upcoming occasions or festivals. You can create your own events. Or you can mark other’s events if you are going to them.

10) YouTube links

To embed a YouTube video in your post, you simply need to copy the YouTube video URL and paste it into the YouTube pop-up. YouTube videos will be embedded in the post.

11) Advertisement (boost post)

Users can boost their posts by paying a small fee ($1 per day). Boosted posts will be labeled as “Sponsored”. The payment method will be Stripe, so users can pay with their debit or credit card. The boosted post will be displayed on the newsfeed, inbox, groups, and pages.

12) Emoji comments

You can add emojis and smileys while posting a comment. They will be saved in Mongo DB and displayed as emojis.

13) Like, dislike, and comments on stories

You can like, dislike, and add comments to a story shared by your friends. Users can see how many likes and comments they have received on their stories.

14) People nearby

A separate page where you can see a list of all people living in your current city. You can send them a friend request and make your friend circle a little bit bigger.

15) Group chat

You can create groups and each group will have its own QR code. Anyone can scan the QR code and join the group and start chatting.

So these are the 15 major functions we added to the social network project. It is developed in Node JS and Mongo DB.

Video streaming web app in Node JS and Mongo DB, MySQL

This project is available in 2 versions:

  • Node JS and Mongo DB
  • Node JS and MySQL

We created a video streaming web app in Node JS and Mongo DB and also in MySQL.

Features

Authentication

User can create an account using his first name, last name, email and password. Passwords can encrypted so even if your database gets hacked, user’s passwords will not be revealed.

Upload Video

User can upload videos. To upload, he needs to provide a thumbnail of the video as well. Thumbnail will be displayed on home screen, history and search pages. Video will only be played from video detail page. User also needs to enter video title, description, tags, categories and playlist (if any). After video is uploaded, he will be redirected to video edit page where he can edit all these details any time he wants.

I am using a Node JS package called “get-video-duration” to automatically get the duration of video and save it in database. This helps in displaying the duration of video so user will know how long the video is.

My Videos

User can see all his uploaded videos and from there he can edit or delete videos as well.

My Channel

A page from where user can set his profile image, his cover image, can see all his uploaded videos and also he can manage playlists from this page. User can add a playlist and it will be displayed on a list. From the list, he can delete any playlist if he no longer needs. If there is any video in that playlist, then user will see the thumbnail of that video. User will also see the number of videos he has in each playlist.

Home Page

On home page, you will see all uploaded videos by all users in descending order. So you will always see the latest videos on top. Each video in list will have title, duration, categories, the number of views it got and the date when it was uploaded.

Video Detail Page

On video detail page, you can the complete detail of that video. Based on cookies, video view is incremented by 1 when you visit that page. On this page, you will see the complete description of that video and also the user name and profile image who uploaded that video. You can subscribe to that channel if you want, and if you have already subscribed then you can remove that channel from your subscription as well. But you cannot subscribe your own channel.

You can like or dislike a video and you will see the counter incremented or decremented by 1. You can post a comment on a video. When you post a comment, a notification will be sent to the video creator so he knows that a new comment has been posted. Other users can reply to your comment and you will get a notification when someone replied to your comment.

On right side of this page, you will see a section at the top where you can place your Google Adsense code if you want. It will help you monetize your website. Below that, you will see a list of all videos under that playlist.

Search

If you click on any category or tag on video detail page, you will be redirected to a new page where all videos in that category or tag will be displayed. This will help you find the videos of your interest. It’s layout is similar to the one you see on home page.

Watch History

Another page that you can access from left sidebar is “History”. Here you can see a list of all videos that you have played. It will also show you the duration of each video you have viewed. So, for example, if a video is 10 minutes long and you watched 3 minutes 45 seconds of it, then you will see a progress bar that tells you that you your watched duration on this video is 3:45.

This will help you find the video in case you saw a video and now you want to see it again. You can delete the videos from watch history as well.

My Subscriptions

When you subscribe a channel, you will see the number gets incremented. But there should be a page where you can see all the channels you have subscribed and also an option to delete any channel from your subscription. You can see that page from left sidebar on each page.

Settings

User can update his first and last name, and he can also change his password as well if he wants.

Screenshots:

Source code:

Video-streaming-web-app-in-Node-JS-and-Mongo-DB
Video-streaming-web-app-in-Node-JS-and-Mongo-DB

Our TrustPilot reviews

TrustPilot-reviews
TrustPilot-reviews

Check out our single-page chat application developed in Vue JS, Node JS, and Mongo DB.

A blog website with admin panel in Node JS and Mongo DB

We have created a blog website with admin panel in Node JS and Mongo DB. It is designed in Bootstrap. And the view engine is EJS.

Version 1.6

Features:

  1. Create, Read, Update, Delete (CRUD) posts from admin panel
  2. 3 themes (Bootstrap, Clean Blog and Materialize CSS)
  3. Comments and replies
  4. Realtime post add, update and delete
  5. Realtime comments and replies
  6. File manager
  7. Post views counter

File manager

File Manager allows you to manage all your uploaded files in one directory. You can simply go to the admin panel and then “File Manager” from the left sidebar. You can upload new files and you can delete existing files as well. On adding or updating a post, you can simply select the already uploaded file and it will be used in the blog post as featured image.

Views counter

Now you can check how many views your post has got. When someone opens your post, the view counter will be incremented and it can be seen on the post’s detail page.

We are constantly adding more features in this blog website with admin panel developed in Node JS and Mongo DB. Check out our single page chat application developed in Vue JS, Node JS and Mongo DB.

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.