Beginner

How to use MQTTChat Cloud Web in a mini website developed with PHP & Mysql.

BY -

In this tutorial we will build a mini website using PHP & Mysql and we will show you how to integrate step by step MQTT CHAT embedded to easily add the chat functionality.

DOWNLOAD CODE
VIDEO DEMO

Let’s start designing the database first.

1- Designing MySQL Database

For this app we need only two tables. users and photos.

users – This table holds the user information like name, email and other profile informations.

photos – This table holds informations about user's photos.

Open phpmyadmin and execute the below sql query to create the required database and tables.


CREATE DATABASE mqtt_chat;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(80)  NOT NULL,
  `surname` varchar(80) NOT NULL,
  `mail` varchar(200) DEFAULT NULL,
  `password` varchar(30) DEFAULT NULL,
  `gender` tinyint(1) NOT NULL DEFAULT '0', 
  `status` varchar(50) DEFAULT 'offline',
  PRIMARY KEY (`id`),
  UNIQUE KEY `mail_UNIQUE` (`mail`)
);

CREATE TABLE `photos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url_min` varchar(255) NOT NULL,
  `url_max` varchar(255) NOT NULL,
  `users_id` int(11) NOT NULL, 
  PRIMARY KEY (`id`),
  KEY `users_id_fk_idx` (`users_id`),
  CONSTRAINT `users_id_fk` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) 
)

2- Creating PHP project

Below is the project structure of the PHP app.

1. Goto your WAMP/MAMP installation location and open the web directory. On windows, it will be c:/wamp/www directory. On Mac, the path will be /Applications/MAMP/htdocs.

2. Inside the web directory (www or htdocs), create a directory named mqtt_chat. This will be the root directory of our project.

3. Inside mqtt_chat folder, create the remaining directories as shown in the above image.

4. Create a file named db_connect.php in include. This file will be used to connect to MySql Database.


    
define('DB_SERVER','localhost');
define('DB_PORT','3306');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME','mqtt_chat');

function MysqlDBConnect()
{
	global $dbh;	
	$dbh = mysql_connect($db_server,DB_USERNAME,DB_PASSWORD,DB_NAME,DB_PORT);
	if (mysql_connect_errno($dbh)) {
		echo "Unable to connect to database due to following error(s). Please check details in configuration file.";
		echo mysql_connect_error($dbh);
		exit();
	}

	mysql_select_db($dbh,DB_NAME);
	mysql_query($dbh,"SET NAMES utf8");
	mysql_query($dbh,"SET CHARACTER SET utf8");
	mysql_query($dbh,"SET COLLATION_CONNECTION = 'utf8_general_ci'");
}

MysqlDBConnect();

5. Now let’s start creating the register page register.php. When registration is successful, user is added to users table and he is redirected to login.php page.


<?php
   include("../include/db_connect.php");
   
   if($_SERVER["REQUEST_METHOD"] == "POST") {
      
      $name = mysqli_real_escape_string($dbh,$_POST['name']);
      $surname = mysqli_real_escape_string($dbh,$_POST['surname']);
      $mail = mysqli_real_escape_string($dbh,$_POST['mail']);
      $password = mysqli_real_escape_string($dbh,$_POST['password']); 
      $gender= mysqli_real_escape_string($dbh,$_POST['gender']);
      
      $sql = "INSERT INTO users (id, name, surname,mail,password,gender)
             VALUES (null,'$name', '$surname', '$mail' ,'$password',$gender)";

      if (mysqli_query($dbh,$sql) === TRUE) {
       header("Location: login.php");
       die();     
      } else {
       $error= "Error: " .$dbh->error;
      }
   }
?>
<html>   
   <head>
     <title>Register Page</title>      
     <style type = "text/css">
         body {
            font-family:Arial, Helvetica, sans-serif;
            font-size:14px;
         }
         label {
            font-weight:bold;
            width:100px;
            font-size:14px;
         }
         .box {
            border:#666666 solid 1px;
         }
      </style>      
  </head>   
   <body bgcolor = "#FFFFFF">	
      <div align = "center">
         <div style = "width:300px; border: solid 1px #333333; " align = "left">
            <div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Register</b></div>
	      <div style = "margin:30px">               
               <form action = "" method = "post">
                  <label>Your Name :</label><input type = "text" name = "name" class = "box"/><br /><br />
                  <label>SurName :</label><input type = "text" name = "surname" class = "box"/><br /><br />
                  <label>Your Email  :</label><input type = "text" name = "mail" class = "box"/><br /><br />
                  <label>Password  :</label><input type = "password" name = "password" class = "box" /><br /><br />
                  <label>gender  :</label><select name="gender" id>
                      <option value="0">Mr</option>
                      <option value="1">Ms</option>
                      <option value="2">Mss</option>
                  </select><br/><br />
                  <input type = "submit" value = " Login " <br /><br />
               </form>                
                <div style = "font-size:11px; color:#333; margin-top:10px">You have account ? <a href="login.php">Login</a></div>
               <div style = "font-size:11px; color:#cc0000; margin-top:10px"></div>
            </div>				
         </div>			
      </div>
   </body>
</html>   

6. Once registration is successfully completed, the user is invited to enter their email address and password to authenticate in login page. If the user account exists and the authentication is ok, the user is then redirected to the main chat page index.php. We use a php session to store the user id.


<?php
   include("../include/db_connect.php");
   session_start();  
   
   if($_SERVER["REQUEST_METHOD"] == "POST") {
      // username and password sent from form       
      $mail = mysqli_real_escape_string($dbh,$_POST['mail']);
      $password = mysqli_real_escape_string($dbh,$_POST['password']); 
      
      $sql = "SELECT id FROM users WHERE mail = '$mail' and password = '$password'";
      $result = mysqli_query($dbh,$sql);
      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);      
     
      // If result matched $myusername and $mypassword, table row must be 1 row
      if($row["id"]>0) {        
         $_SESSION['userid'] = $row["id"];         
         header("location: index.php");
      }else {
         $error = "Your Login Name or Password is invalid";
      }
   }
?>
<html>   
   <head>
      <title>Login Page</title>      
      <style type = "text/css">
         body {
            font-family:Arial, Helvetica, sans-serif;
            font-size:14px;
         }
         label {
            font-weight:bold;
            width:100px;
            font-size:14px;
         }
         .box {
            border:#666666 solid 1px;
         }
      </style>      
   </head>   
   <body bgcolor = "#FFFFFF">	
      <div align = "center">
         <div style = "width:300px; border: solid 1px #333333; " align = "left">
            <div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>				
            <div style = "margin:30px">               
               <form action = "" method = "post">
                  <label>Your Email  :</label><input type = "text" name = "mail" class = "box"/><br /><br />
                  <label>Password  :</label><input type = "password" name = "password" class = "box" /><br/><br />
                  <input type = "submit" value = " Login "/><br />
               </form>                
                <div style = "font-size:11px; color:#333; margin-top:10px">D'ont have account ? <a href="register.php">Register</a></div>
                <div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>   
            </div>				
         </div>			
      </div>
   </body>
</html>

7. In index.php page, we will integrate MQTTChat. For that you have to access first to your MQTTChat client area, add your website domain name and then choose the package that suits you. In this tutorial we will add a test domain named "test123.com" and we will choose the free MQTTChat pack MQTTChat_CLOUD_1000_USERS_24_MONTHS (0$);

mqtt chat add new domain

8. MQTTChat subscription activation is almost instantaneous. Go to the Settings tab of your admin panel to get your APP_ID and APP_SECRET. You will need them during installation. mqtt chat code

9. Now we will integrate MQTTChat to main page index.php. But before we verify that the user is logged using session userid variable and we get current user informations (required by MQTTChat) from database. It is necessary to edit default values in the code provided by MQTTChat by values that we get from database.


<?php
include("../include/db_connect.php");
session_start();
?>
<!DOCTYPE html>
<html>
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://cluster1.telifoun.com/rest/en/mqttchat.js?appId=mqttchat-54182281"></script>  
    </head>
<body>

<?php
/** check user is logged in **/
if(!isset($_SESSION["userid"])){
header("Location: login.php");
die();   
}
/** get user infos from database **/
$userid=$_SESSION["userid"];
$sql = "SELECT * from users where id=$userid";
$result = mysqli_query($dbh,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);   
?>
 

<div id="mqttchat" 
 data-layout="embedded"
 class="mqttchat-default"
 data-user-id="<?=$row['id']?>"          
 data-user-name="<?=$row['name']?>" 
 data-user-surname="<?=$row['surname']?>" 
 data-user-avatar=""
 data-user-link=""
 data-user-gender="<?=$row['gender']?>"
 data-width="900"
 data-height="500">          
</div>                

</body>
</html>

mqtt chat embedded

10. Since width and height have been set in MQTTChat data settings. Chat interface will remains fixed and does not adapt to the screen resolution. For the chat interface to become responsive, you have to remove data-width and data-height data. In this case chat interface will have the same height and width of #mqttchat parent div (.chat-box).


<?php
include("../include/db_connect.php");
session_start();
?>
<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cluster1.telifoun.com/rest/en/mqttchat.js?appId=mqttchat-54182281"></script>
        <style type = "text/css">
         .chat-box{
            height: 90vh;
            width:100%;
            padding: 0;
            margin: 0;
           }
      </style> 
    </head>
<body>

<?php
/** check user is logged in **/
if(!isset($_SESSION["userid"])){
header("Location: login.php");
die();   
}
/** get user infos from database **/
$userid=$_SESSION["userid"];
$sql = "SELECT * from users where id=$userid";
$result = mysqli_query($dbh,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);   
?>
    

<div class="chat-box">
<div id="mqttchat" 
 data-layout="embedded"
 class="mqttchat-default"
 data-user-id="<?=$row['id']?>"          
 data-user-name="<?=$row['name']?>" 
 data-user-surname="<?=$row['surname']?>" 
 data-user-avatar=""
 data-user-link=""
 data-user-gender="<?=$row['gender']?>"
 >          
</div> 
</div>              

</body>
</html>
mqtt chat embedded

11. If we want to try MQTTChat docked, just change integration code in index.php as follows.


<?php
include("../include/db_connect.php");
session_start();
?>
<!DOCTYPE html>
<html>
    <head>
         <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
        <script src="https://cluster1.telifoun.com/rest/en/mqttchat.js?appId=mqttchat-54182281"></script>      
    </head>
<body>

<?php
/** check user is logged in **/
if(!isset($_SESSION["userid"])){
header("Location: login.php");
die();   
}
/** get user infos from database **/
$userid=$_SESSION["userid"];
$sql = "SELECT * from users where id=$userid";
$result = mysqli_query($dbh,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);   
?>

<div id="mqttchat" 
 data-layout="docked"
 class="mqttchat-default"
 data-user-id="<?=$row['id']?>"          
 data-user-name="<?=$row['name']?>" 
 data-user-surname="<?=$row['surname']?>" 
 data-user-avatar=""
 data-user-link=""
 data-user-gender="<?=$row['gender']?>"
 >          
</div>              

</body>
</html>
mqtt chat docked

3- Testing Chat.

1. To be able to test MQTTChat functionalities, you must add other users by opening register.php page in another browser, for example firefox.

mqtt chat embedded

4- Update user's status

1. You can save user's presence status in database and show the list of online users or filter users by presence status. The feature is not enabled by default, to activate it you must define a valid URL in your site and enable the option from your MQTTChat client area.
in this tutorial we will receive server status callbacks in statusCallback.php file.

mqtt chat status callback

2. To save user's status in database, use for example the code below.


<?php

include("../include/db_connect.php");

/* get JSON Post Data  */
$json = file_get_contents('php://input');
/* get PHP data Array */
$data = json_decode($json);

/* get userid */
$userid=  $data["userid"];
/* get new status */
$status = $data["status"];

$sql = "UPDATE users set status='$status' where id=$userid";

if (mysqli_query($dbh,$sql) === TRUE) {
  echo "user status updated successfully";
} else {
  echo "Error updating user status: " . $dbh->error;
}
?>

5- Use MQTTChat Events

1. In profile.php page we want to be notified when logged user receives a new message and continue to receive audio and video calls but without displaying the chat interface. We will therefore use two MQTTChat events: mqttchat-not-read-messages-count-update and mqttchat-incoming-message.
To be able to connect to MQTTChat without displaying chat interface, add a div #mqttchat without class attribute. Only userid data is required.


    
<?php
   include("../include/db_connect.php");
   session_start(); 
   if(isset($_SESSION["userid"])){
    /** get user infos from database **/
    $userid=$_SESSION["userid"];
    $sql = "SELECT * from users where id=$userid";
    $result = mysqli_query($dbh,$sql);
    $row = mysqli_fetch_array($result,MYSQLI_ASSOC);     
   }else{
   header("Location: login.php");
   die();      
   }
?>
<html>
   
   <head>
      <title>Profie Page</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
     <script src="https://cluster1.telifoun.com/rest/en/mqttchat.js?appId=mqttchat-54182281"></script>
      <style type = "text/css">
         body {
            font-family:Arial, Helvetica, sans-serif;
            font-size:14px;
         }
         label {
            font-weight:bold;
            width:100px;
            font-size:14px;
         }
         .box {
            border:#666666 solid 1px;
         }
         .m-notification{
             margin: 10px;
            background-color: #cc0000;
            color:#FFFFFF;
            width:160px;
            display: none;          
         }
      </style>
      
      <script>
       $(document).ready(function() {
           
        $(document).on("mqttchat-not-read-messages-count-update",function(e){
          if(e.mqttchat_data.n>0){
             $('.m-notification').show();
             $('.m-notification').html(e.mqttchat_data.n+" new messages");
          }else{
            $('.m-notification').hide();
            $('.m-notification').html(""); 
          }
        });
        
        $(document).on("mqttchat-incoming-message",function(e){
         console.log(e.mqttchat_data);
        });
        
        });    
      
      </script>
      
   </head>
   
   <body bgcolor = "#FFFFFF">	
       
         <div align = "center">             
         <div class="m-notification"></div>              
         <div style = "width:300px; border: solid 1px #333333; " align = "left">
         <div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>User Profile</b></div>       
           <table>
               <tr><td>Name</td><td><?=$row["name"]?></td></tr> 
               <tr><td>surname</td><td><?=$row["surname"]?></td></tr> 
           </table>
         </div>
         </div>       
       
       
        <div id="mqttchat"  data-user-id="<?=$row['id']?>" >
            

   </body>
</html>

2. You can still receive audio and video calls even if the chat interface is not displayed.

6- MQTTChat web notifications

1. To enable web push notifications, simply download and unzip a service worker mqttchat_sw_1_0.js at the root directory of website. If integration is well done, you will see that user is registred to push notification in browser console.


In this tutorial we developed a basic chat application in pHP and Mysql. We have shown that it is very fast and easy to integrate MQTTChat. Indeed in a few lines of codes you can develop a complete chat application. If you are facing any issue in this tutorial, please comment in below discussions.


2020 © MQTT-CHAT.com Inc.