Contact us form – PHP & MySQL

Learn how to create a working contact us form in PHP and MySQL. We will show a simple form in HTML. It will send the request to the PHP server. And PHP will store the form fields in MySQL database.

Demo

Almost every website has a page from where visitors can interact with the administrator or owner of the website. That page usually referred to as “contact us”. The purpose of this page is to solve problems, confusions of visitors who find difficulty using the website. If you are providing services online then it is a great tool to get custom orders from visitors and turn your visitors into real customers. As mentioned earlier, that it is a need for almost every website, so we are going to teach you how you can create that page for your website.

What does our “contact us” page do ?

The contact us page we are going to design and develop, will send an eamil to the administrator or owner of website (you) and it will also save its record in the database for future use. We are also going to make it secure from spam using CSRF (cross-side request forgery). As it is a contact us page and every hacker knows that if they submit this form then either an email will be sent or an entry in the database will be made. So someone can make a script that will send the request on the server 1000 times and that may cause crashing your server.

That is where CSRF tokens are used and we are going to use them in our contact us form. Also, we will add the functionality to highlight the messages which were unread and create a button for administrator to mark any message as read. We will also add the functionality to delete the message from database because sometimes people starts sending irrelevant promotional emails.

Database

First we will create a MySQL table in our database. Assuming that you already have a database, so you can simply open your phpMyAdmin and paste the following query:

CREATE TABLE IF NOT EXISTS inbox (
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name TEXT NOT NULL,
    email TEXT NOT NULL,
    message TEXT NOT NULL,
    is_read BOOLEAN NOT NULL,
    created_at DATETIME NOT NULL
);

This will create a table named “inbox” if already not exists. If you already have a table with that name and you are using it for some other module, you can change its name which best suits you and easy to remember for you. This table will have an auto increment ID which will be used to uniquely identify each message received from users. Name, email and message which are simple text attributes and an is_read field. This field will be used to highlight the messages which are unread. Unread messages will have this attribute as 0 and read messages will have 1. Last will be the created_at attribute, if you ever worked on Laravel then you most probably be aware of this attribute. This attribute holds the date and time when this entry is made, meaning the date and time when the message is sent from contact form.

Create a form

<?php
    session_start();
?>

<form method="POST" action="contact.php">
    <?php
        $_token = md5(time());
        $_SESSION["_token"] = $_token;
    ?>
    <input type="hidden" name="_token" value="<?php echo $_token; ?>" />

    <p>
        <label>Name</label>
        <input type="text" name="name" required>
    </p>

    <p>
        <label>Email</label>
        <input type="email" name="email" required>
    </p>

    <p>
        <label>Message</label>
        <textarea name="message" required></textarea>
    </p>

    <p>
        <input type="submit" name="contact_us" value="Send message">
    </p>
</form>

First, we are starting the PHP session. We will need the PHP sessions for CSRF tokens. Then we have created a form with a POST method and action to the page where we will process this form. After that, we are creating a CSRF token, we are creating it my converting the current timestamp into md5 hash which will create a strong hashed string. Then we are storing this in PHP built-in session variable so we can use it in next page, make sure you have started the session before using any session variable. The token created needs also be stored in a hidden input field inside the form so it will be sent along with other fields. The form will have name, email and message of the user and a submit button which when clicked will submit the form.

Process the form

Create a new file named “contact.php” or whatever the value you have given to action attribute on previous step, and paste the following code in it. We will explain each step of it:

<?php
    session_start();

    // check if the form submits
    if (isset($_POST["contact_us"]))
    {
        $_token = $_POST["_token"];

        // check CSRF token
        if (isset($_SESSION["_token"]) && $_SESSION["_token"] == $_token)
        {
            // remove the token so it cannot be used again
            unset($_SESSION["_token"]);

            // connect with database
            $conn = mysqli_connect("localhost:8889", "root", "root", "yourdbname");

            // get and validate input fields from SQL injection
            $name = mysqli_real_escape_string($conn, $_POST["name"]);
            $email = mysqli_real_escape_string($conn, $_POST["email"]);
            $message = mysqli_real_escape_string($conn, $_POST["message"]);
            $is_read = 0;

            // sending email
            $headers = 'From: YourWebsite <admin@yourwebsite.com>' . "\r\n";
            $headers .= 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            
            $to = "admin@gmail.com";
            $subject = "New Message";

            $body = "<h1>Message from:</h1>";
            $body .= "<p>Name: " . $name . "</p>";
            $body .= "<p>Email: " . $email . "</p>";
            $body .= "<p>Message: " . $message . "</p>";

            mail($to, $subject, $body, $headers);

            // saving in database
            $sql = "INSERT INTO inbox(name, email, message, is_read, created_at) VALUES ('" . $name . "', '" . $email . "', '" . $message . "', " . $is_read . ", NOW())";
            mysqli_query($conn, $sql);

            echo "<p>Your message has been received. Thank you.</p>";
        }
        else
        {
            echo "<p>Something went wrong.</p>";
        }

        header("refresh: 5; url=contact.php");
    }
?>

First we have started the session so we can verify CSRF token. Then we are checking if the form is submitted. Then we are validating the form under CSRF (cross-side request forgery). If the token in the session matches with the value of the hidden input field then it means that the request is sent from contact us and is ok to process. Otherwise, we will be displaying a message “Something went wrong”. In the next line, we are removing the token from session variable so it cannot be used again. Then we are connecting with database. Then we are getting all input fields in separate variables. And also we are validating each field under SQL injection attack using PHP built-in mysqli_real_escape_string. We also have a variable is_read and it’s value is set to 0. So, by default all the incoming messages will be marked as unread.

Send email to admin

Then we are sending an email to the administrator. Headers are used to send additional information but here we are using especially because our email will have HTML tags in it. You can specify the email where you want to receive in $to variable. Set the $subject of email as per desire. Similarly, you can set the content of email in $body variable. We are displaying all input field values in the email body. To send an email, we are using PHP built-in mail function but if you are testing in localhost then you need to use PHPMailer library. You can learn how to use PHPMailer in this post.

Finally, we are saving the record in MySQL database. You just need to enter all fields in the INSERT query VALUES clause and also a variable is_read. The created_at field will have the value of current date & time which can be get from MySQL built-in function NOW(). Then the query is executed and a success message is displayed to the user. If all goes well, then you will see a new email in your inbox and also a new row in your phpMyAdmin database’s inbox table.

Display inbox in admin panel

In your admin panel, create a file named “inbox.php” and display all entries from contact us form. Highlight the unread messages and add 2 buttons; to mark as read and to delete.

<?php
    // connect with database
    $conn = mysqli_connect("localhost:8889", "root", "root", "yourdbname");

    // get all inbox messages such that latest messages are on top
    $sql = "SELECT * FROM inbox ORDER BY id DESC";
    $result = mysqli_query($conn, $sql);

?>

    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }
        th, td {
            padding: 10px;
        }
    </style>

    <table class="table">

        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Message</th>
            <th>Actions</th>
        </tr>

<?php while ($row = mysqli_fetch_object($result)): ?>
        <tr style="<?php $row->is_read ? '' : 'background-color: lightgray;'; ?>">
            <td><?php echo $row->name; ?></td>
            <td><?php echo $row->email; ?></td>
            <td><?php echo $row->message; ?></td>
            <td>
                <?php if (!$row->is_read): ?>
                    <form method="POST" action="mark-as-read.php" onsubmit="return confirm('Are you sure you want to mark it as read ?');">
                        <input type="hidden" name="id" value="<?php echo $row->id; ?>">
                        <input type="submit" value="Mark as read">
                    </form>
                <?php endif; ?>

                <form method="POST" action="delete-inbox-message.php" onsubmit="return confirm('Are you sure you want to delete this ?');">
                    <input type="hidden" name="id" value="<?php echo $row->id; ?>">
                    <input type="submit" value="Delete">
                </form>
            </td>
        </tr>
<?php endwhile; ?>

    </table>

This will connect with database. Get all messages from inbox table sorted by id in descending order. So that the latest messages come at the top. Create a table tag and inside it create a row for headings. We have also applied some CSS to make it look good, border will give a line on all four sides of the table. border-collapse will remove the duplicate borders between th and td tags. padding is applied only on th & td which will give some space between border and content of th & td. Then we are creating a loop on all records fetched from query and for each record we are creating a table row <tr> and in each table row, we are displaying name, email and message. If the message status is unread, then we are setting the background-color of table row to lightgray just to highlight it among other rows.

Actions <td>

In the last column, we are creating 2 forms; to mark specific message as read and to delete the message. First form will be created under a condition that if the message status is unread. Because if the message is already readed then no need to mark it as read. Second form will be to delete the message from database.

Before submitting these forms, we want to display a confirmation box so if user accidentally clicks on the delete button. Then it should prompt the user for confirmation and not delete the message immediately. On both forms, we have added an attribute onsubmit. This is an event which will be called when the form is submitted and a Javascript code is ran. We have to return true or false, return true means to submit the form. And false means to prevent the form from submitting.

In Javascript we have a built-in function confirm, this will show a prompt box with 2 buttons “Yes” or “No”. If user press Yes then it returns true, else it returns false. So when you click the submit button, it will ask for confirmation. If you press Yes only then it will send the request to the next page.

Mark message as read

Create a file named “mark-as-read.php” in your admin panel. Here we will simply set the message’s status to read and show a success message.

<?php
    // connect with database
    $conn = mysqli_connect("localhost:8889", "root", "root", "yourdbname");

    // prevent from SQL injection
    $id = mysqli_real_escape_string($conn, $_POST["id"]);
    
    // set the message as read
    $sql = "UPDATE inbox SET is_read = 1 WHERE id = " . $id;
    mysqli_query($conn, $sql);

    // display a success message
    echo "<p>Message has been marked as read.</p>";
?>

Firt we are connecting with database. Then we are getting the ID from hidden input field and also validating it from SQL injection. Then we are running a query to set the is_read value to 1 using the unique ID. Finally, a simple success message is displayed. The next time you see the inbox in your admin panel, you will see that message un-highlighted and only 1 button to delete the message. The button to mark as read will not be displayed. If you go to “inspect element” you will see that the form for mark as read is not created at all.

Delete the message

Now we need to create a file in admin panel named “delete-inbox-message.php“. Here we will run the delete query which will remove that row from inbox table.

<?php
    // connect with database
    $conn = mysqli_connect("localhost:8889", "root", "root", "yourdbname");

    // prevent from SQL injection
    $id = mysqli_real_escape_string($conn, $_POST["id"]);
    
    // delete the message
    $sql = "DELETE FROM inbox WHERE id = " . $id;
    mysqli_query($conn, $sql);

    // display a success message
    echo "<p>Message has been deleted.</p>";
?>

All the steps are same except the query and message. The query will search for message using it’s ID in the “inbox” table and delete it. The success message will be displayed. Next time you open the inbox page on your admin panel, you will no longer see that message in that list. However, if you want to show realtime messages on admin panel i.e. when someone send a message through contact us form. You do not have to refresh the page on admin panel to see new messages. All new incoming messages will automatically be displayed there, check this post if you want to have that feature too.

Dynamic custom carousel – HTML & Javascript

In this article, we are going to teach you how you can create a dynamic custom carousel. If you are a web developer, you might have already came across with bootstrap carousel, which is basically a slider. Although, it shows you the functionality to show slides, move next/previous and many more. But nothing gives you more control than writing the code by yourself. Sometimes, you just want to learn the algorithms that how these sliders are created. So we will create a dynamic custom carousel using HTML, Javascript & PHP. If you do not want to fetch the slider images from database, you can skip the PHP part and jumps to the Javascript part.

What we are going to do ?

We will be fetching data from database and display in slides, thus makes our custom carousel dynamic. The database we will be using is named “tutorials” and the table whom we will be fetching data is “posts”. It has 3 fields (id, title, image). We will not be using ID attribute, it is just for unique identification and relationship between different tables. We will be displaying title and image in each slide.

First, create a database named “tutorials”. Create a table named “posts” and insert data in it using the following query:

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` text NOT NULL,
  `image` text NOT NULL
);

--
-- Dumping data for table `posts`
--

INSERT INTO `posts` (`id`, `title`, `image`) VALUES
(1, 'image 1', 'https://i.pinimg.com/originals/f8/d9/a7/f8d9a791ed9cd56f4970513d8797459d.png'),
(2, 'image 2', 'https://i.pinimg.com/564x/32/93/81/32938198ee16b5b2339a9071c8eb454f.jpg'),
(3, 'image 3', 'https://i.pinimg.com/564x/f3/ac/41/f3ac41a686ceff77bf9473827df5476c.jpg');

Slides

Then you need to connect with its database using PHP and fetch all the images for slider. Again, you can create a simple PHP array and enter the URL of all the images and their titles which you wanted to be displayed in each slide. But in most of the cases, there are images which are added from admin panel. In this case, you need to simply fetch all images from that table and display them in slides.

<?php
    $conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");

    $result = mysqli_query($conn, "SELECT * FROM posts");

    $count = 0;
    $posts = array();
    while ($row = mysqli_fetch_object($result)):
        array_push($posts, $row);
        ?>

        <div class="post <?php echo $count == 0 ? 'active' : ''; ?>">
            <p><?php echo $row->title; ?></p>
            <img src="<?php echo $row->image; ?>" style="width: 500px;">
        </div>

        <?php
        $count++;
    endwhile;
?>

You have seen that we created a <div> tag and it has 2 classes, post & active. But active class will be given only to the first div element. This is because we want to show the first slides first. To display other slides we will create 2 buttons next & previous. We have also created a PHP array $posts which will have all the slides. Use this variable to move next and previous slides. We will also teach you how you can convert a PHP variable, object or an array into a Javascript variable. For each slide, we are displaying its title and an image. Now we will apply some CSS to hide the slides which does not have a class “active”. And display the only slide which has an “active” class.

<style>
    .post {
        display: none;
    }
    .post.active {
        display: block;
    }
</style>

Slide indicators

Now we will create a <div> which will hold the next and previous slides indicators. If you have ever used bootstrap carousel then you might already be familiar with it. If you are not, indicators are the buttons which are used to show the next or previous slide. The basic algorithm is, if the next indicator is clicked, then you get next slide <div> element, hide the currently active <div> and show the next slide. Same goes for previous indicator, only different is, you have to get the previous <div> element instead of the next. We will also be displaying next slide’s name so the user can know which slide will be displayed next. It will be treated just as a reference.

<div class="links">
    <div class="previous-post" onclick="showPrevious();">
        <div style="display: contents; cursor: pointer;">
            <p>
                <b>previous post</b>
            </p>

            <p id="previous-post-title"></p>
        </div>
    </div>

    <div class="next-post" onclick="showNext();" style="margin-left: 100px;">
        <div style="display: contents; cursor: pointer;">
            <p>
                <b>next post</b>
            </p>

            <p id="next-post-title"></p>
        </div>
    </div>
</div>

Using PHP variable in Javascript

Now we will come to the part where we promised that we will teach you how you can convert a PHP variable into a Javascript variable. If you have followed the tutorial so far, you might already have a $posts PHP array. Now you want to use this in your Javascript code. Simply we will create a hidden input field, give it an ID so we can get it in Javascript. And set the value to that PHP array. But since $posts is an array, so we have to convert that into JSON format. We can do that simply by calling a PHP built-in function json_encode. Now when the array is converted into JSON, some characters might create trouble for you while setting it as a value of input field. So you have to wrap your function inside another PHP built-in function htmlentities.

<input type="hidden" id="posts" value="<?php echo htmlentities(json_encode($posts)); ?>">

Next and previous slide

Now when the page loads, we will get this input field value using its ID. Since we converted that into JSON, now we have to parse it in Javascript objects or array. We can do that by simply calling a function JSON.parse. It will convert the PHP variable into a proper Javascript variable. Now you can use this array anywhere in your Javascript code. The following code will show the next indicator only if there is a slide afterwards. Similarly it will show the previous indicator only if there is a slide before.

<script>
    var currentIndex = 0;

    window.addEventListener("load", function () {
        postsArray = document.getElementById("posts").value;
        postsArray = JSON.parse(postsArray);

        renderTitle();
    });

    function showPrevious() {
        currentIndex--;

        var previous = document.querySelector(".post.active").previousElementSibling;
        document.querySelector(".post.active").className = "post";
        previous.className = "post active";

        renderTitle();
    }

    function showNext() {
        currentIndex++;

        var next = document.querySelector(".post.active").nextElementSibling;
        document.querySelector(".post.active").className = "post";
        next.className = "post active";

        renderTitle();
    }

    function renderTitle() {
        document.querySelector(".previous-post").style.visibility = "hidden";
        document.querySelector(".next-post").style.visibility = "hidden";

        if (postsArray[currentIndex + 1] != null) {
            document.querySelector(".next-post").style.visibility = "visible";
            document.getElementById("next-post-title").innerHTML = postsArray[currentIndex + 1].title;
        }

        if (postsArray[currentIndex - 1] != null) {
            document.querySelector(".previous-post").style.visibility = "visible";
            document.getElementById("previous-post-title").innerHTML = postsArray[currentIndex - 1].title;
        }
    }
</script>

Explanation

You can also see the renderTitle() function, we will come back to that later. First we created a variable named currentIndex and initialize it with 0. That is the index of current slide visible to the user.

When the next or previous indicator is clicked, we are calling a function which will increment the value of currentIndex if next indicator is clicked. And decrement the value if previous indicator is clicked.

Then we are getting the next slide’s <div> using nextElementSibling and removing the “active” class from currently active slide. Finally we are setting the “active” class to next slide. That’s how current slide will be hidden and next slide will be displayed.

renderTitle()

Now come to the renderTitle() function. It is called 3 times, one when the page loads, one when next slide indicator is clicked. And one when previous slide indicator is clicked. This function has 3 purposes: first to hide both next and previous slide indicators. Second is to show the next indicator only if there is a slide next. Similarly show the previous indicator only if there is a slide before.

We already have a postsArray array which holds all the slide elements so we can check easily. Third purpose of this function is to show the title of next and previous slide. So, the user can know on which slide he is going to see next.

Hope this tutorial helps you create your own dynamic custom carousel which you can customize and design as per your need. You can add more features to it if you want. Try adding CSS animations, like making the slide move left or right when next and previous is clicked.

Also try to change the slide automatically after 5 seconds. The list of features can go on because it is a dynamic custom carousel and anyone can add more features in it as per needs. If you a minimalism lover, then you can also remove elements from it which you do not like. For example, you can remove the next and previous slide title to make space and make it more minimal.

Movie ticket booking website – PHP and MySQL

A movie ticket booking website is created in PHP and MySQL following the principles of Object-Oriented Programming (OOP) and Model-View-Controller (MVC). Google Adsense supported. CSRF (Cross-site Request Forgery) is protected.

FeaturesFreePremium
User authenticationYesYes
Admin loginYesYes
Add, edit, and delete categoriesYesYes
Add, edit, and delete moviesYesYes
Add, edit, and delete cinemasYesYes
Add, edit, and delete celebritiesYesYes
Set cast of each movieYesYes
Show currently playing movies in all cinemasYesYes
Show biography and filmography of celebritiesYesYes
Book tickets onlineNoYes
SeasonsNoYes
Receive payments from Stripe & PayPalNoYes

Demo

Free version:

https://drive.google.com/file/d/16fmMA5tDe6VqzhDmJ_KvwvaDvrojKscJ/view?usp=sharing

Feature list:

  1. Admin login.
  2. Add, Edit, and Delete categories.
  3. CRUD operation on movies.
  4. Add, Edit, Delete cinemas.
  5. Play movies in cinemas.
  6. Add, Edit, Delete celebrities.
  7. Add cast in movies.
  8. Show currently playing movies in all cinemas.
  9. Login and registration.
  10. User home.
  11. Movie detail.
  12. Show biography and filmography of celebrities.
  13. Seasons
  14. Receive payments online (Stripe & PayPal)

How to setup:

Our TrustPilot reviews

TrustPilot-reviews
TrustPilot-reviews

Disable scroll on input type number – Javascript

Ever come across a problem where you enter some value in input type number and while you scroll down or up, you will see that the value of that input field is changed. It is because of the default behavior of the browser, it increments or decrements the value of input fields having “type” attribute valued as “number” as long as the user is scrolling inside that input field. So, let’s learn how to disable scroll on input type number for these situations.

However, there are multiple ways to prevent this behavior. But the simplest solution we came across is by removing the focus from that input field as long as the user is scrolling inside that input field. We are calling it “simplest” because it does not even need jQuery.

yes NO JQUERY !!!

Just paste the following code at the end of the file where you want to disable this scrolling behavior:

var inputTypeNumbers = document.querySelectorAll("input[type=number]");
for (var a = 0; a < inputTypeNumbers.length; a++) {
	inputTypeNumbers[a].onwheel = function (event) {
		event.target.blur();
	};
}

Explanation

querySelectorAll will return all the nodes that matches the selector passed in as an argument. We are selecting all input fields which have a field attribute having value as “number”. This will return an array which we can use to loop through all nodes.

Next, we are looping through all input type numbers and inside this loop. We can perform a specific action on each node. We are overriding onwheel event, which is called whenever we move the mouse wheel inside the input field. In this event, we are receiving a variable from parameter named as “event”. It contains all the functions and attributes of this event.

We have an object named “target” in this event object which holds the actual input field node. Although we can use the “inputTypeNumbers[a]” inside the function event, it is better to use the event.target object. All input fields in HTML5 have a function named “blur()” which removes the focus from that input field. Calling this function will remove the focus from that input field and thus the scrolling of numbers will not occur.

That’s how you can disable scroll on input type number using Javascript’s “onwheel” event.

Detect page leave – HTML & Javascript

Preview image from input type file before upload – Javascript

In this article, we will learn how to preview image before upload from input type file using Javascript. A FileReader object is used.

The following code will display an input type file from where the user can select an image file. As soon as he selects the image, it’s preview will be displayed in an image tag. This is useful when you want to show the user the image he selected, before saving it in the database. So the user must know that he has picked the correct image.

<script>
	function previewImage() {
		var file = document.getElementById("file").files
		if (file.length > 0) {
			var fileReader = new FileReader()

			fileReader.onload = function (event) {
				document.getElementById("preview").setAttribute("src", event.target.result)
			}

			fileReader.readAsDataURL(file[0])
		}
	}
</script>

<form method="POST" action="/" enctype="multipart/form-data">
	<input type="file" name="file" id="file" accept="image/*" onchange="previewImage();">

	<img id="preview">
</form>

Explanation

Form encoding type will be used to upload the file on the server-side (PHP). Give your input type file a unique ID so it can be accessed in Javascript. We have created an image tag where a preview of the selected file will be displayed. Give a unique ID to this image tag too. A function on onchange event on input type file will be called whenever user select some file from dialog. We are also adding an attribute accept=”image/*” that will make sure that the user selects only the image files like JPEG, PNG etc.

In this function, first we are checking if the user has selected any file. We are creating a FileReader object, it is used to read the file. With this file reader object, we are calling a function named readAsDataURL, it will read the content of a file as URL. That URL will be used to set the “src” attribute of our image tag.

onload event will be called when the file is fully read by file reader object. In this function, we are simply setting the “src” attribute of our image tag. event.target refers to the original file reader object and “result” is the actual URL of selected file.

Since you have learned how you can preview an image before upload from input type file using Javascript. Learn also how to upload, download and delete files in PHP.

[wpdm_package id=’247′]

PHP – Add Dynamic Rows in Table Tag

Learn how to add dynamic rows in a table tag in HTML and Javascript. And also save the data in MySQL database using PHP. If you want to know how to do this in React, check our this tutorial.

Introduction

Suppose you are trying to generate an invoice for your customers. You wanted to have a functionality where you will be able to add multiple items in an invoice. A simple table tag will be created from where the user will be able to add multiple items. You have added a button labeled as “Add Item” which when clicked will create a new row to add an item.

Now it might sound easy but technically you have to create rows dynamically. Whenever a user clicks on the “Add Item” button, a new row inside table tag should be created and it must be an array as items can be multiple. Then these arrays should be stored in the database using a loop iteration. Following this tutorial, you will be able to do so.

We will be creating 2 tables, although to explain this tutorial only 1 table would be enough but teaching with 2 will help to understand better when you are working on existing projects. We will have 1 table for storing invoices basic data, for example, customer name, etc, and the second table for storing items in that invoice.

“invoices” table

Our first table name is “invoices” and it will have just 2 fields, unique auto-increment ID and customer name. And the second table will be named “items” and have the product name, quantity, etc and also a foreign key that reference for invoice ID.

To add dynamic rows, we are using a <table> tag that will create a table layout so we will add rows in <tbody> tag. As discussed earlier, all rows will be in an array that needs to be stored in the database, so we will create a <form> tag that will help to do this. We are setting the method to POST as the data might be sensitive and long, and action attribute as current file name, you can change this if you want to send data to a different page.

Customer field

We are creating a simple input field for customer name that will be stored in the “invoices” table, you can place your other fields here. Then we are creating a <table> tag and inside it, we will be displaying the number of items, item name, and item quantity. Make sure to give <tbody> tag a unique ID so we can append new rows in it using Javascript.

Below them, we are creating a button which when clicked will call a Javascript function from where we can add a new row inside that table. And finally, a submit button which when clicked will submit the form and we have to save that data in database.

<form method="POST" action="index.php">
	<input type="text" name="customerName" placeholder="Enter customer name" required>

	<table>
		<tr>
			<th>#</th>
			<th>Item Name</th>
			<th>Item Quantity</th>
		</tr>
		<tbody id="tbody"></tbody>
	</table>

	<button type="button" onclick="addItem();">Add Item</button>
	<input type="submit" name="addInvoice" value="Add Invoice">
</form>

Add/delete row

Now we need to create a function which when clicked will add a new node in the <tbody> tag. We have created a variable for the number of items and we are incrementing it on each click. Whenever this function called we are creating a <tr> tag and adding input fields for name and quantity in <td> tags. Notice the “[]” with the input name attribute, this tells that this field will be an array. Lastly, we are creating a new row using tbody function called insertRow() and appending the <tr> HTML in it.

<script>
	var items = 0;
	function addItem() {
		items++;

		var html = "<tr>";
			html += "<td>" + items + "</td>";
			html += "<td><input type='text' name='itemName[]'></td>";
			html += "<td><input type='number' name='itemQuantity[]'></td>";
            html += "<td><button type='button' onclick='deleteRow(this);'>Delete</button></td>"
		html += "</tr>";

		var row = document.getElementById("tbody").insertRow();
		row.innerHTML = html;
	}

function deleteRow(button) {
    items--
    button.parentElement.parentElement.remove();
    // first parentElement will be td and second will be tr.
}
</script>

Style the table

Now we are going to apply some styles on our table just to make it look a little bit good.

<style type="text/css">
	table {
		width: 100%;
		border-collapse: collapse;
	}
	table tr td,
	table tr th {
		border: 1px solid black;
		padding: 25px;
	}
</style>

Add record in database

Now we just need to store this data in our database. The following code must be put at the top of your file. Our database name is “tutorials” but it will be different in your case, make sure to change the DB name accordingly. Next, check if the form is submitted, the if block will only run after the user submits the form. Get the customer name and insert that in the “invoices” table, it is rather simple.

Remember we added “invoiceId” as a foreign key in “items” table. So, we have to get the newly inserted AUTO-INCREMENT ID. Then we are looping through all the added items. You can either use the “itemName” input field or “itemQuantity” and insert them in “items” table with same invoice ID.

<?php

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

	if (isset($_POST["addInvoice"]))
	{
		$customerName = $_POST["customerName"];

		$sql = "INSERT INTO invoices (customerName) VALUES ('$customerName')";
		mysqli_query($conn, $sql);
		$invoiceId = mysqli_insert_id($conn);

		for ($a = 0; $a < count($_POST["itemName"]); $a++)
		{
			$sql = "INSERT INTO items (invoiceId, itemName, itemQuantity) VALUES ('$invoiceId', '" . $_POST["itemName"][$a] . "', '" . $_POST["itemQuantity"][$a] . "')";
			mysqli_query($conn, $sql);
		}

		echo "<p>Invoice has been added.</p>";
	}

?>

That’s it, the job is done. At this point, you will be able to select multiple items. And add dynamic rows in table tag and inserting them in the database as well. Complete source file along with SQL exported file which will help you to understand the structure of database.

[wpdm_package id=’239′]

Custom auto complete view – Vanilla Javascript

Learn how to create a custom auto complete view in vanilla Javascript. Auto complete view is a feature in which an input field predicts the rest of a word a user is typing. In most frequently fields like city names, users can typically enter some words. And wait for seeing the suggestions to accept one of several cities.

Auto complete view speeds up human-computer interactions. It correctly predicts the word a user intends to enter after only a few characters have been typed into a text input field. It works best in domains with a limited number of possible words (such as in command-line interpreters). When some words are much more common (such as when addressing an e-mail), or writing structured and predictable text (as in source code editors).

Google

In search engines like Google, auto complete view provide users with suggested queries or results as they type their query in the search box. This is also commonly called autosuggest or incremental search. This type of search often relies on matching algorithms that forgive entry errors. Such as phonetic Soundex algorithms or the language-independent Levenshtein algorithm. The challenge remains to search large indices or popular query lists in under a few milliseconds. So, that the user sees results pop up while typing.

Nothing gives you more control than writing code by yourself.

Unknown

Auto complete view can have an adverse effect on individuals and businesses when negative search terms are suggested. Autocomplete has now become a part of reputation management as companies linked to negative search terms such as scam, complaints and fraud seek to alter the results. Google in particular have listed some of the aspects that affect how their algorithm works. But this is an area that is open to manipulation.

Example

Suppose you have a list of values that you want to populate in an input field as user types. Give users an ability to select an item from that list and store the data. For example, if you have a list of products, you can display product title. But once any value is selected, you can send the product ID in database. Although there are many libraries on the internet to do this job. But they are limited in customizations and you have to remember their function names and parameters and options etc.

Lets get started

First we are going to create an input field that will have an ability to call a Javascript function as soon as user types something in it. We are attaching the “onkeyup” attribute on that field which will be called for every key pressed by the user. We are also giving this field an ID and name attribute:

  • ID will be use in Javascript to populate suggestions based on this field value.
  • Name will be use in PHP where form data will be sent. You can handle this as per your project.

Form’s method and action attribute depends on your project, you can adjust them as per your needs. We have also created a hidden field which will set the ID of selected product. So we will be displaying product title in suggestions. Also, when user select one product, it’s ID will be put in this hidden field. Lastly, we have a div where all suggested products will be displayed.

<form method="POST" action="send-data.php">
    <input type="text" id="product" name="product" onkeyup="onKeyUp();">
    <input type="hidden" id="productCode" name="productCode">
    <div id="products-list"></div>
</form>

Send HTTP request

First we will create a function for “onkeyup” event that we attached on previous step. In this function, we are getting value from product’s input field. We will get the suggested products only if the input field has at-least 3 words in it. Because sending HTTP request on each word would be very costly and it does not make sense at all. When you search for some product you already know first 4 or 5 characters of it. Even in case of cities, most people know at-least 3-4 characters of what they want to search. Displaying suggestions on each word would be really annoying for users.

Then in div where we wanted to show the suggested products, we will first show a loading message. So that the user knows that it is searching for products and the location where suggested products will be displayed. Then we are sending an AJAX request, the request method is GE. So it does not require any headers in the request.

URL of AJAX request

Second parameter in open function is the name of file, we will create that file in next step. In same parameter, we are sending user entered words in the URL so we can get them in that PHP file. At the end of this function we are sending the request. But before sending, we are attaching an event which will be called when the response is successfully received from server.

From get-products.php file which we will create in next step, we will receive all the suggested products based on value of input field. The response sent from PHP to Javascript will be in JSON string format, so we have to convert (parse) that string to Javascript objects and arrays. Then we will loop through all the suggested products and display them in paragraph. A separate variable is created which will store all the HTML content of the autocomplete view. Finally, we are setting this HTML variable value to div using its unique ID.

<script>
    function onKeyUp() {
        var product = document.getElementById("product");

        if (product.value.length >= 3) {
            document.getElementById("products-list").innerHTML = "Loading...";

            var ajax = new XMLHttpRequest();
            ajax.open("GET", "get-products.php?product=" + product.value, true);

            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 += "<p>" + data[a].productName + "</p>";
                    }

                    document.getElementById("products-list").innerHTML = html;
                }
            };

            ajax.send();
        }
    }
</script>

Get suggested products

So we are sending HTTP request after 3 words entered by the user. And sending those 3 words to the server to fetch suggested products that match their title with those 3 words. Now we need to create a file that will match the product’s title with those words and return them all as an array. So we are first connecting with the database, get the user input field from URL.

Search that value in the database based on the products table’s title field (it might be different as per your need). Executing that query will return a $result object. It will have all pieces of information about the result which is received from the database. For example, number of rows, columns in each row, each row’s content, etc.

mysqli_fetch_all

You can use the mysqli_fetch_all function to return all rows at once. But this function does not work in some PHP versions. So what we are going to do, is to loop through each record and push them in our created array one-by-one. We will be using while loop to continue loop until all rows are fetched. At the end, we will have a PHP array will all the suggested products.

But we need them in Javascript, so we need to convert that array into JSON string format and in Javascript we are already converting that string back to Javascript arrays and objects.

get-products.php

<?php

	$conn = mysqli_connect("localhost", "root", "root", "classicmodels");
	$product = $_GET["product"];

	$sql = "SELECT * FROM products WHERE productName LIKE '%" . $product . "%'";
	$result = mysqli_query($conn, $sql);

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

?>

Select product from suggestions

At this point, as the user starts typing the input field, after 3 words a list of suggested products will be displayed. Now we need to give the user an ability to select a product from this suggested list. First, we need to attach on “onclick” listener to the product’s title in a suggestions list that will call a Javascript function whenever the user selects a product from the list.

In that function we are going to need a selected product ID, so we are adding a custom attribute data-id whose value will be the product ID that should be set in the hidden input field. In that function, we are getting the selected product ID and setting this in the hidden product code field. Also, we are emptying the div so the suggestions will be removed once an item is selected from the list.

Lastly, in input field we are setting product’s title as a value because the user has only entered 3 words, once he selects some item from the list, that value will be set in his input field.

function selectProduct(self) {
	var productCode = self.getAttribute("data-id");
	document.getElementById("productCode").value = productCode;
	document.getElementById("products-list").innerHTML = "";
	document.getElementById("product").value = self.innerHTML;
}

// Inside AJAX response
for (var a = 0; a < data.length; a++) {
	html += "<p onclick='selectProduct(this);' data-id='" + data[a].productCode + "'>" + data[a].productName + "</p>";
}

Applying styles

Although this part has nothing to do with functionality, but it is always good to do some work on the design and make it look good. Add a CSS class to suggested products single paragraph, and create a <style> tag anywhere in your file and use that CSS class to applying styles as per your needs.

// Inside the loop in AJAX response, give CSS class
html += "<p class='product-list-item' onclick='selectProduct(this);' data-id='" + data[a].productCode + "'>" + data[a].productName + "</p>";

<style>
    .product-list-item {
        background: darkgray;
        color: white;
        width: 200px;
        padding: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>

That’s how you can create a customized auto complete view in HTML and Javascript.

[wpdm_package id=’235′]

Send dynamic email from HTML & CSS template – PHP

By the end of this tutorial, you will be able to send a dynamic email in PHP. Along with any beautifully designed template in HTML, CSS or Bootstrap. We will be using the template named “Invoice” from this website:
https://www.dyspatch.io/resources/templates/airmail/

It’s a pretty basic template and great to learn.
After downloading the template, you will see something like this:

All are static values. So let’s make them dynamic.

First you have to put all the template code in 1 separate file and named it “payment.php”, make sure to have all CSS code in this file. No external CSS file should be used because it will not appear in email.

Now, you have to replace the values you want to change and replace them with {{key}} for example, if you want to make coupon code dynamic, you will do something like this:

Coupon code {{coupon_code}}

Now, coming back to the file from where you want to send email, let’s say “send-mail.php”, first you have to get the template file by:

<?php
    $email = file_get_contents("payment.php");
    echo $email;
?>

This will display your email template in “send-mail.php” file. In order to replace the {{coupon_code}} with your dynamic value, you have to use the str_replace function of PHP. It accepts 3 parameters:

  1. Value to be replaced
  2. New value
  3. String from which to replace
<?php
    $email = file_get_contents("payment.php");
    $email = str_replace("{{coupon_code}}", "1234567", $email);
    echo $email;
?>

Now we are going to add {{key}} on every static value in template which needs to be dynamic. After that, you need to create an array in your “send-mail.php” file and use the same function for all static values.

<?php
    $email = file_get_contents("payment.php");
    $email = str_replace("{{coupon_code}}", "1234567", $email);
    $variables = array(
        "{{coupon_code}}" => 1234,
        "{{invoice}}" => 5678,
        "{{card_ending}}" => 9876,
        "{{username}}" => "Adnan"
   );

    foreach ($variables as $key => $value)
        $email = str_replace($key, $value, $email);
    echo $email;
?>

Now, you will be able to see your template with correct values. You can send the mail using the following 2 methods:

  1. PHP built-in mail() function
  2. Using PHPMailer library

Built-in mail() function

You can call the function:

<?php
    // Your subject goes here
    $subject = 'Payment Invoice';

    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    // Enter receiver's email address
    mail("receiver_email@gmail.com", $subject, $email, $headers);
?>

Using PHPMailer library

You can install the library using composer in your project:

composer require phpmailer/phpmailer

and follow the guide from here: https://github.com/PHPMailer/PHPMailer


If you do not want to use composer, you can download manually from the following link and follow the guide: https://github.com/adnanafzal565/php-mailer

Hit the “send mail” button and you will receive an email similar to this:

So that’s how you can send a dynamic email in PHP from any HTML template. Also, learn how you can attach a link to the file to download in an email from here.

If you have any problems in following this, feel free to ask in the comments section below.

[wpdm_package id=’76’]