PHP Chatbot Tutorial: Welcome, aspiring web developers! Ever wondered how those helpful little chat windows on websites work? While professional chatbots can be incredibly complex, building a simple one is a fantastic way to get started with backend web development using PHP and interacting with a database.
Table of Contents (PHP Chatbot Tutorial)
In this comprehensive (PHP Chatbot Tutorial), step-by-step tutorial, we’ll guide you through creating a basic chatbot application using PHP and MySQL. This bot will be able to respond to a few predefined questions, store the conversation, and provide a simple chat interface. Let’s get building!
What You Will Learn:
- Setting up a MySQL database for your chat data.
- Connecting PHP to your database.
- Creating a simple HTML and CSS interface for the chat.
- Using JavaScript and AJAX to send messages without reloading the page.
- Writing PHP code to handle user input and generate bot responses.
Prerequisites (PHP Chatbot Tutorial)
Before we begin, make sure you have the following installed and set up:
- A Web Server with PHP and MySQL: This could be a local development environment like XAMPP, WAMP (for Windows), MAMP (for macOS), or a remote hosting account. These packages typically include Apache (or Nginx), PHP, and MySQL.
- A Code Editor: Any text editor will work, but an IDE like VS Code, Sublime Text, or Notepad++ will make coding easier with features like syntax highlighting.
- A Web Browser: Chrome, Firefox, Edge, etc.
- Basic Understanding of HTML, CSS, and PHP: This tutorial is for beginners, but some familiarity with these technologies will be helpful.
Step 1: Setting Up Your Database (PHP Chatbot Tutorial)
Our chatbot needs a place to store messages and the bot’s predefined responses. We’ll use MySQL for this.
First, you need to create a database. You can do this using a database management tool like phpMyAdmin (which comes with XAMPP/WAMP/MAMP) or by using the MySQL command line.
Let’s assume your database name will be youtube
(as used in the provided files).
Next, we need to create the necessary tables. You’ve provided a database.sql
file which contains the SQL commands to create two tables: chatbot_hints
and message
.
Here’s the content of database.sql
:
SQL
CREATE TABLE `chatbot_hints` (
`id` int(11) NOT NULL,
`question` varchar(100) NOT NULL,
`reply` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `chatbot_hints`
--
INSERT INTO `chatbot_hints` (`id`, `question`, `reply`) VALUES
(1, 'HI||Hello||Hola', 'Hello, how are you.'),
(2, 'How are you', 'Good to see you again!'),
(3, 'what is your name||whats your name', 'My name is Vishal Bot'),
(4, 'what should I call you', 'You can call me Vishal Bot'),
(5, 'Where are your from', 'I m from India'),
(6, 'Bye||See you later||Have a Good Day', 'Sad to see you are going. Have a nice day');
-- --------------------------------------------------------
--
-- Table structure for table `message`
--
CREATE TABLE `message` (
`id` int(11) NOT NULL,
`message` text NOT NULL,
`added_on` datetime NOT NULL,
`type` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `message`
--
INSERT INTO `message` (`id`, `message`, `added_on`, `type`) VALUES
(1, 'Hi', '2020-04-22 12:41:04', 'user'),
(2, 'Hello, how are you.', '2020-04-22 12:41:05', 'bot'),
(3, 'what is your name', '2020-04-22 12:41:22', 'user'),
(4, 'My name is Vishal Bot', '2020-04-22 12:41:22', 'bot'),
(5, 'Where are your from', '2020-04-22 12:41:30', 'user'),
(6, 'I m from India', '2020-04-22 12:41:30', 'bot'),
(7, 'Go to hell', '2020-04-22 12:41:41', 'user'),
(8, 'Sorry not be able to understand you', '2020-04-22 12:41:41', 'bot'),
(9, 'bye', '2020-04-22 12:41:46', 'user'),
(10, 'Sad to see you are going. Have a nice day', '2020-04-22 12:41:46', 'bot');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `chatbot_hints`
--
ALTER TABLE `chatbot_hints`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `message`
--
ALTER TABLE `message`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `chatbot_hints`
--
ALTER TABLE `chatbot_hints`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `message`
--
ALTER TABLE `message`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
COMMIT;
Explanation of Tables:
chatbot_hints
: This table stores the predefined questions and their corresponding replies.id
: A unique identifier for each hint.question
: The user’s input that the bot will look for (you can use||
to separate multiple variations of the same question).reply
: The bot’s response to the question.
message
: This table will store the conversation history.id
: A unique identifier for each message.message
: The content of the message (either user or bot).added_on
: The timestamp when the message was sent.type
: Indicates whether the message is from the ‘user’ or the ‘bot’.
How to import the SQL file:
- Open your database management tool (like phpMyAdmin).
- Select the database you created (e.g.,
youtube
). - Find the “Import” tab or option.
- Choose the
database.sql
file from your computer. - Click “Go” or “Import”.
This will create the two tables and populate chatbot_hints
with some initial question/reply pairs.
Step 2: Setting Up Your Project Files (PHP Chatbot Tutorial)
Create a folder for your project within your web server’s document root (e.g., htdocs
for Apache). Let’s call the folder php-chatbot
.
Inside this folder, create the following files:
index.php
style.css
database.inc.php
get_bot_message.php
- Create a subfolder named
image
and inside it, place two small image files for user and bot avatars. You can use placeholders or simple icons nameduser_avatar.png
andbot_avatar.png
.
Your project structure should look something like this:
php-chatbot/
├── index.php
├── style.css
├── database.inc.php
├── get_bot_message.php
└── image/
├── user_avatar.png
└── bot_avatar.png
Step 3: Connecting to the Database (database.inc.php
)
This file is crucial for establishing a connection to your MySQL database from your PHP scripts.
Here’s the code for database.inc.php
:
PHP
<?php
$con=mysqli_connect('localhost','root','','youtube');
?>
Explanation:
mysqli_connect('localhost','root','','youtube')
: This line attempts to establish a connection to the MySQL database using themysqli
extension.'localhost'
: The hostname of your database server. If it’s on the same server as your web server,localhost
is usually correct.'root'
: Your MySQL username. Important: In a production environment, you should never use theroot
user with no password. This is done here for simplicity in a local development setup.''
: Your MySQL password. Again, this is left blank for a typical local XAMPP/WAMP setup. Use a strong password in production.'youtube'
: The name of the database you created in Step 1.
If the connection fails, this script won’t output an error by default, which isn’t ideal for debugging. In a real application, you would add error handling here.
Step 4: Styling the Chat Interface (style.css
)
This file contains the CSS code to style the chat appearance. The provided code uses some basic styles to format the messages, input area, and overall layout.
Here’s the content of style.css
:
CSS
.unread {
cursor: pointer;
background-color: #f4f4f4;
}
.messages-box {
max-height: 28rem;
overflow: auto;
}
.online-circle {
border-radius: 5rem;
width: 5rem;
height: 5rem;
}
.messages-title {
float: right;
margin: 0px 5px;
}
.message-img {
float: right;
margin: 0px 5px;
}
.message-header {
text-align: right;
width: 100%;
margin-bottom: 0.5rem;
}
.text-editor {
min-height: 18rem;
}
.messages-list li.messages-you .messages-title {
float: left;
}
.messages-list li.messages-you .message-img {
float: left;
}
.messages-list li.messages-you p {
float: left;
text-align: left;
}
.messages-list li.messages-you .message-header {
text-align: left;
}
.messages-list li p {
max-width: 60%;
padding: 5px;
border: #e6e7e9 1px solid;
}
.messages-list li.messages-me p {
float: right;
}
.ql-editor p {
font-size: 1rem;
}
This CSS uses classes like .messages-box
, .messages-me
, and .messages-you
to control the layout and appearance of the chat messages, differentiating between user and bot messages by floating them to the right and left respectively. It also sets a maximum height for the message area and enables scrolling.
Step 5: Creating the Frontend (index.php
)
This file contains the HTML structure of our chat interface, includes the necessary CSS and JavaScript libraries (Bootstrap and jQuery via CDN), displays existing messages from the database, and handles sending new messages using AJAX.
Here’s the code for index.php
:
PHP
<?php
date_default_timezone_set('Asia/Kolkata');
include('database.inc.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<title>PHP Chatbot</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link href="style.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-md-center mb-4">
<div class="col-md-6">
<div class="card">
<div class="card-body messages-box">
<ul class="list-unstyled messages-list">
<?php
$res=mysqli_query($con,"select * from message");
if(mysqli_num_rows($res)>0){
$html='';
while($row=mysqli_fetch_assoc($res)){
$message=$row['message'];
$added_on=$row['added_on'];
$strtotime=strtotime($added_on);
$time=date('h:i A',$strtotime);
$type=$row['type'];
if($type=='user'){
$class="messages-me";
$imgAvatar="user_avatar.png";
$name="Me";
}else{
$class="messages-you";
$imgAvatar="bot_avatar.png";
$name="Chatbot";
}
$html.='<li class="'.$class.' clearfix"><span class="message-img"><img src="image/'.$imgAvatar.'" class="avatar-sm rounded-circle"></span><div class="message-body clearfix"><div class="message-header"><strong class="messages-title">'.$name.'</strong> <small class="time-messages text-muted"><span class="fas fa-time"></span> <span class="minutes">'.$time.'</span></small> </div><p class="messages-p">'.$message.'</p></div></li>';
}
echo $html;
}else{
?>
<li class="messages-me clearfix start_chat">
Please start
</li>
<?php
}
?>
</ul>
</div>
<div class="card-header">
<div class="input-group">
<input id="input-me" type="text" name="messages" class="form-control input-sm" placeholder="Type your message here..." />
<span class="input-group-append">
<input type="button" class="btn btn-primary" value="Send" onclick="send_msg()">
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function getCurrentTime(){
var now = new Date();
var hh = now.getHours();
var min = now.getMinutes();
var ampm = (hh>=12)?'PM':'AM';
hh = hh%12;
hh = hh?hh:12;
hh = hh<10?'0'+hh:hh;
min = min<10?'0'+min:min;
var time = hh+":"+min+" "+ampm;
return time;
}
function send_msg(){
jQuery('.start_chat').hide();
var txt=jQuery('#input-me').val();
var html='<li class="messages-me clearfix"><span class="message-img"><img src="image/user_avatar.png" class="avatar-sm rounded-circle"></span><div class="message-body clearfix"><div class="message-header"><strong class="messages-title">Me</strong> <small class="time-messages text-muted"><span class="fas fa-time"></span> <span class="minutes">'+getCurrentTime()+'</span></small> </div><p class="messages-p">'+txt+'</p></div></li>';
jQuery('.messages-list').append(html);
jQuery('#input-me').val('');
if(txt){
jQuery.ajax({
url:'get_bot_message.php',
type:'post',
data:'txt='+txt,
success:function(result){
var html='<li class="messages-you clearfix"><span class="message-img"><img src="image/bot_avatar.png" class="avatar-sm rounded-circle"></span><div class="message-body clearfix"><div class="message-header"><strong class="messages-title">Chatbot</strong> <small class="time-messages text-muted"><span class="fas fa-time"></span> <span class="minutes">'+getCurrentTime()+'</span></small> </div><p class="messages-p">'+result+'</p></div></li>';
jQuery('.messages-list').append(html);
jQuery('.messages-box').scrollTop(jQuery('.messages-box')[0].scrollHeight);
}
});
}
}
</script>
</body>
</html>
Explanation:
- PHP Includes:
date_default_timezone_set('Asia/Kolkata');
: Sets the default timezone for date and time functions. You might want to change this to your local timezone.include('database.inc.php');
: Includes the database connection file.
- HTML Structure:
- Sets up a basic HTML5 document.
- Includes Bootstrap CSS for basic styling and layout, and our custom
style.css
. - Includes jQuery and Bootstrap JavaScript libraries via CDN.
- Uses Bootstrap grid system (
container
,row
,col-md-6
) to center the chat box on the page. - The chat messages are displayed within a
div
with the classmessages-box
and aul
with the classmessages-list
. - An input field (
input-me
) and a button (Send
) are provided for typing and sending messages.
- PHP for Displaying Existing Messages:
$res=mysqli_query($con,"select * from message");
: Fetches all messages from themessage
table.if(mysqli_num_rows($res)>0)
: Checks if there are any messages in the database.- The
while
loop iterates through the results:- It retrieves the message content, timestamp, and type (
user
orbot
). - Based on the
type
, it sets the CSS class (messages-me
ormessages-you
), avatar image, and display name. - It formats the time using
date('h:i A', $strtotime)
. - It constructs an HTML list item (
<li>
) for each message with the appropriate classes and content and appends it to the$html
variable.
- It retrieves the message content, timestamp, and type (
echo $html;
: Prints the generated HTML for the messages.- If there are no messages, it displays a “Please start” message.
- JavaScript:
getCurrentTime()
: A helper function to get the current time inhh:mm AM/PM
format.send_msg()
: This function is called when the “Send” button is clicked.- It hides the “Please start” message if it’s visible.
- It gets the text from the input field (
#input-me
). - It immediately adds the user’s message to the chat display using jQuery’s
.append()
, giving the user instant feedback. - It clears the input field.
jQuery.ajax({...})
: This is the core part that sends the user’s message to the server without a full page reload (AJAX).url:'get_bot_message.php'
: The PHP script that will handle the message and generate a bot reply.type:'post'
: Sends the data using the HTTP POST method.data:'txt='+txt
: The data being sent to the server, wheretxt
is the user’s message.success:function(result){...}
: This function is executed when the server (get_bot_message.php
) successfully responds.result
: The response from the server (which will be the bot’s message).- It constructs the HTML for the bot’s message and appends it to the chat display.
jQuery('.messages-box').scrollTop(jQuery('.messages-box')[0].scrollHeight);
: Scrolls the message box to the bottom to show the latest message.
Step 6: Handling Messages and Generating Replies (get_bot_message.php
)
This PHP script receives the user’s message via AJAX, looks for a matching predefined reply in the chatbot_hints
table, saves both the user and bot messages to the message
table, and sends the bot’s reply back to the frontend.
Here’s the code for get_bot_message.php
:
PHP
<?php
date_default_timezone_set('Asia/Kolkata');
include('database.inc.php');
$txt=mysqli_real_escape_string($con,$_POST['txt']);
$sql="select reply from chatbot_hints where question like '%$txt%'";
$res=mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0){
$row=mysqli_fetch_assoc($res);
$html=$row['reply'];
}else{
$html="Sorry not be able to understand you";
}
$added_on=date('Y-m-d h:i:s');
mysqli_query($con,"insert into message(message,added_on,type) values('$txt','$added_on','user')");
$added_on=date('Y-m-d h:i:s');
mysqli_query($con,"insert into message(message,added_on,type) values('$html','$added_on','bot')");
echo $html;
?>
Explanation:
- PHP Includes:
- Sets the timezone and includes the database connection.
$txt=mysqli_real_escape_string($con,$_POST['txt']);
:$_POST['txt']
: Retrieves the user’s message sent from the frontend via the AJAX POST request.mysqli_real_escape_string()
: Crucially important for security. It escapes special characters in the input string to prevent SQL injection attacks. Always use this (or prepared statements) when inserting user-provided data into a database query.
$sql="select reply from chatbot_hints where question like '%$txt%'";
: This is the query to find a bot reply.select reply from chatbot_hints
: Selects thereply
column from thechatbot_hints
table.where question like '%$txt%'
: This is the matching logic. It searches for any row where thequestion
column contains the user’s input ($txt
). The%
are wildcards meaning “match any characters before or after the input”.- Note: This is a very basic matching method. A real-world chatbot would use more sophisticated techniques like natural language processing (NLP) or keyword matching with variations. The
||
in thequestion
column ofchatbot_hints
is not directly used in this specific query but is intended to allow for multiple question phrases per reply entry if the matching logic were more advanced (e.g., splitting the string by||
).
$res=mysqli_query($con,$sql);
: Executes the SQL query.if(mysqli_num_rows($res)>0)
: Checks if the query returned any results (meaning a matching question was found).- If a match is found:
$row=mysqli_fetch_assoc($res);
: Fetches the matching row as an associative array.$html=$row['reply'];
: Sets the bot’s reply ($html
) to the found reply.
- If no match is found:
$html="Sorry not be able to understand you";
: Sets a default “I don’t understand” message.
- If a match is found:
- Saving Messages to Database:
$added_on=date('Y-m-d h:i:s');
: Gets the current timestamp.mysqli_query($con,"insert into message(message,added_on,type) values('$txt','$added_on','user')");
: Inserts the user’s message into themessage
table.mysqli_query($con,"insert into message(message,added_on,type) values('$html','$added_on','bot')");
: Inserts the bot’s generated reply into themessage
table.
echo $html;
: Sends the bot’s reply back to the frontend. This is theresult
that the JavaScript AJAX call receives inindex.php
.
Step 7: Running Your Chatbot (PHP Chatbot Tutorial)
- Make sure your web server (Apache) and database server (MySQL) are running.
- Place the
php-chatbot
folder (containing all the files and theimage
subfolder) in your web server’s document root. - Open your web browser and navigate to the address where you placed the folder. If you’re using XAMPP locally, this would likely be
http://localhost/php-chatbot/
.
You should see the chat interface. Type one of the questions you added to the chatbot_hints
table (like “Hi”, “How are you”, or “what is your name”) and press “Send”. You should see your message appear, followed by the bot’s reply. The conversation will also be saved in your message
database table.
How It All Works Together (PHP Chatbot Tutorial)
- When you open
index.php
, the PHP code fetches any existing messages from themessage
table and displays them. - You type a message in the input field.
- When you click “Send”, the
send_msg()
JavaScript function is triggered. - This function immediately adds your message to the displayed list for a smooth user experience.
- It then uses AJAX to send your message (
txt
) toget_bot_message.php
in the background. get_bot_message.php
receives your message, looks for a matching reply inchatbot_hints
, and determines the bot’s response.- Both your message and the bot’s reply are saved to the
message
table. get_bot_message.php
sends the bot’s reply back to the browser.- The
success
function in the JavaScript onindex.php
receives the bot’s reply (result
) and adds it to the chat display.
This process happens without the page reloading, making the chat feel more interactive.
Potential Improvements and Next Steps (PHP Chatbot Tutorial)
This is a very simple chatbot. Here are some ideas for how you could expand and improve it:
- More Complex Bot Logic: Instead of just using
LIKE
, implement more sophisticated matching, regular expressions, or even integrate with a natural language processing API. - Learning Capability: Could the bot learn from conversations or be trained on a larger dataset?
- User Management: Add user accounts and allow multiple users to chat (this would require a much more complex architecture, likely involving websockets for real-time communication).
- Error Handling: Add more robust error handling for database connections and queries.
- Security: Implement better security practices, especially if exposing this to the internet (e.g., prepared statements instead of
mysqli_real_escape_string
, input validation, protection against cross-site scripting (XSS)). - Front-end Enhancements: Improve the user interface, add features like typing indicators, emojis, or file uploads.
- Configuration: Store database credentials in a separate configuration file outside the webroot.
This PHP chatbot tutorial provides a solid foundation for understanding how to build interactive web applications using PHP, MySQL, and AJAX. By following these steps, you’ve successfully created your first bot and learned about key concepts in web development!