How to Insert Emoji using PHP in Comments

Last modified on October 2nd, 2018 by Vincy.

Online comments systems and chat applications will not be complete without an option to insert emojis. Emojis are emotive images to share emotions while sending messages. The Facebook-like social media websites popularized the usage of emoji by providing the messaging interface with emoji support.

Generally, people share emotions by creating emojis with symbols for example :-) ;-). By having the graphical emotive icons, it is fun to convey a variety of emotions through messages easily.

how-to-insert-emoji-using-php-in-comments

In this code, we are going to add an option to insert emojis while adding comments. We have already seen,  how to create a comment system using PHP. The same comments system example is going to be used in this example by integrating an emoji picker.

I have integrated a third-party library known as emoji-picker. This is a jQuery based library used to insert emoji picker control in the comment system interface. Download emoji-picker library and include it to the application.

Comments System Interface with Emoji Picker

The HTML code shows the form to insert comments with emoji picker. There will be inputs for entering the user’s name and message while adding comments. Previously, we have added like/unlike and more features for a PHP comments system.

The emoji picker is initialized with the reference of the message box element. The comment box element has to be set with the HTML5 data attributes data-emojiable=true and data-emoji-input =unicode. After initialization, the emoji picker control will be displayed at the top right corner of the comment message box.

<html>
<head>
<link href="vendor/emoji-picker/lib/css/emoji.css" rel="stylesheet">
<link href="style.css" rel="stylesheet">

<link rel="stylesheet"
	href="http://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<title>How to Insert Emoji using PHP in Comments</title>
<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<script src="vendor/emoji-picker/lib/js/config.js"></script>
<script src="vendor/emoji-picker/lib/js/util.js"></script>
<script src="vendor/emoji-picker/lib/js/jquery.emojiarea.js"></script>
<script src="vendor/emoji-picker/lib/js/emoji-picker.js"></script>
</head>

<body>
	<div class="output-container">
		<h2>How to Insert Emoji using PHP in Comments</h2>

		<div class="comment-form-container">
			<form id="frm-comment">
				<div class="input-row">
					<input type="hidden" name="comment_id" id="commentId"
						placeholder="Name" /> <input class="input-field" type="text"
						name="name" id="name" placeholder="Name" />
				</div>

				<div class="input-row">
					<p class="emoji-picker-container">
						<textarea class="input-field" data-emojiable="true"
							data-emoji-input="unicode" type="text" name="comment"
							id="comment" placeholder="Add a Message">  </textarea>
					</p>
				</div>

				<div>
					<input type="button" class="btn-submit" id="submitButton"
						value="Add a Comment" />
					<div id="comment-message">Comment Added Successfully!</div>
				</div>


			</form>
		</div>
		<div id="output"></div>

	</div>
</body>
</html>

jQuery Script to Enable Emoji-Picker

This is the code to add an emoji picker in the comment box. In this script, the EmojiPicker().discover() function is invoked, by setting the emoji selector that contains the data-emojiable attribute.

The emoji icons source path and more other default options will also set to the emoji picker instance at the time of initialization. 

$(function () {
    // Initializes and creates emoji set from sprite sheet
    window.emojiPicker = new EmojiPicker({
        emojiable_selector: '[data-emojiable=true]',
        assetsPath: 'vendor/emoji-picker/lib/img/',
        popupButtonClasses: 'icon-smile'
    });

    window.emojiPicker.discover();
});

jQuery AJAX Code to List and Add Comments with Emojis

In this script, the comment-list and the comment-add request is raised from a jQuery AJAX function to the PHP. On submitting the user’s comment or replies with emoji selection, the AJAX call is executed to update the database. 

After getting a response based on the action requested, the AJAX success block will handle the UI update dynamically. Comments and replies are shown in a hierarchical order as parent-child UI elements. 

<script>
    function postReply(commentId) {
        $('#commentId').val(commentId);
        $("#name").focus();
    }

    $("#submitButton").click(function () {
        $("#comment-message").css('display', 'none');
        var str = $("#frm-comment").serialize();

        $.ajax({
            url: "comment-add.php",
            data: str,
            type: 'post',
            success: function (response)
            {
                var result = eval('(' + response + ')');
                if (response)
                {
                    $("#comment-message").css('display', 'inline-block');
                    $("#name").val("");
                    $("#comment").val("");
                    $("#commentId").val("");
                    listComment();
                } else
                {
                    alert("Failed to add comments !");
                    return false;
                }
            }
        });
    });

    $(document).ready(function () {
        listComment();
    });

    function listComment() {
        $.post("comment-list.php",
                function (data) {
                    var data = JSON.parse(data);

                    var comments = "";
                    var replies = "";
                    var item = "";
                    var parent = -1;
                    var results = new Array();

                    var list = $("<ul class='outer-comment'>");
                    var item = $("<li>").html(comments);

                    for (var i = 0; (i < data.length); i++)
                    {
                        var commentId = data[i]['comment_id'];
                        parent = data[i]['parent_comment_id'];

                        if (parent == "0")
                        {
                            comments =  "<div class='comment-row'>"+
                            "<div class='comment-info'><span class='posted-by'>" + data[i]['comment_sender_name'] + "</span></div>" + 
                            "<div class='comment-text'>" + data[i]['comment'] + "</div>"+
                            "<div><a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a></div>"+
                            "</div>";
                            var item = $("<li>").html(comments);
                            list.append(item);
                            var reply_list = $('<ul>');
                            item.append(reply_list);
                            listReplies(commentId, data, reply_list);
                        }
                    }
                    $("#output").html(list);
                });
    }

    function listReplies(commentId, data, list) {

        for (var i = 0; (i < data.length); i++)
        {
            if (commentId == data[i].parent_comment_id)
            {
                var comments = "<div class='comment-row'>"+
                " <div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" + 
                "<div class='comment-text'>" + data[i]['comment'] + "</div>"+
                "<div><a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a></div>"+
                "</div>";
                var item = $("<li>").html(comments);
                var reply_list = $('<ul>');
                list.append(item);
                item.append(reply_list);
                listReplies(data[i].comment_id, data, reply_list);

            }
        }
    }
</script>

PHP Code to Add List Comments

The PHP and jQuery AJAX part have no magic and work as usual PHP AJAX programming that we learned already.

After adding the user comments along with the emojis to the database, the PHP code will print the comments which will be read as a response in the AJAX script. This response data will be updated in the comments UI.

On a successful database insert, a success message will be displayed in the comments form. In a previous tutorial, we have seen how to enrich comment system by displaying response text with jQuery fade in / fade away effect.

comment-list.php

<?php
require_once ("db.php");
$record_set = array();
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        array_push($record_set, $row);
    }
}
echo json_encode($record_set);
?>

comment-add.php

<?php
require_once ("db.php");
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date('Y-m-d H:i:s');

$query = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES (?,?,?,?)";

$sql_stmt = $conn->prepare($query);

$param_type = "dsss";
$param_value_array = array(
    $commentId,
    $comment,
    $commentSenderName,
    $date
);
$param_value_reference[] = & $param_type;
for ($i = 0; $i < count($param_value_array); $i ++) {
    $param_value_reference[] = & $param_value_array[$i];
}
call_user_func_array(array(
    $sql_stmt,
    'bind_param'
), $param_value_reference);

$sql_stmt->execute();
?>

Database design

CREATE TABLE IF NOT EXISTS `tbl_comment` 
(
`comment_id` int(11) NOT NULL,
`parent_comment_id` int(11) DEFAULT NULL,
`comment` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
`comment_sender_name` varchar(40) CHARACTER SET utf8 NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=utf8mb4;

PHP Comments System Output with Emoji Selector

This screenshot shows the output of the PHP comments system with emoji picker. It also shows the list of comments with emojis inserted with the text messages.

php-comment-sytem-output-with-emoji-picker

Download

This PHP code tutorial was published on October 2, 2018.

↑ Back to Top

Share this Article