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.


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.

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

<link rel="stylesheet"

<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>

	<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 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>

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

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


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'

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. 

    function postReply(commentId) {

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

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

    $(document).ready(function () {

    function listComment() {
                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>"+
                            var item = $("<li>").html(comments);
                            var reply_list = $('<ul>');
                            listReplies(commentId, data, reply_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>"+
                var item = $("<li>").html(comments);
                var reply_list = $('<ul>');
                listReplies(data[i].comment_id, data, reply_list);


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.


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);


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(
$param_value_reference[] = & $param_type;
for ($i = 0; $i < count($param_value_array); $i ++) {
    $param_value_reference[] = & $param_value_array[$i];
), $param_value_reference);


Database design

`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,

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.



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

↑ Back to Top

Share this Article