-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.php
40 lines (33 loc) · 1.67 KB
/
bot.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
// bot.php
require 'database_config.php'; // Assume this file contains your DB connection settings
try {
// Establish the database connection using PDO
$conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo '<div class="chat botmessages"><img src="/assets/aibot.png" alt="avatar" style="width:30px;"> Connection failed: ' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</div>';
die('Connection failed: ' . $e->getMessage());
}
// Define a function to get the chatbot response
function getChatbotResponse($conn, $message)
{
$stmt = $conn->prepare("SELECT response FROM chatbot WHERE messages LIKE CONCAT('%', :message, '%')");
$stmt->bindParam(':message', $message);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result) {
return $result['response'];
}
return "Sorry, I can't understand you.";
}
if (isset($_POST['messageValue'])) {
$userMessage = $_POST['messageValue'];
$response = getChatbotResponse($conn, $userMessage);
// Sanitize the user's message for HTML output
$userMessageHTML = htmlspecialchars($userMessage, ENT_QUOTES, 'UTF-8');
echo '<div class="chat botmessages"><img src="/assets/aibot.png" alt="avatar" style="width:30px;"> ' . htmlspecialchars($response, ENT_QUOTES, 'UTF-8') . '</div>';
} else {
echo '<div class="chat botmessages"><img src="/assets/aibot.png" alt="avatar" style="width:30px;"> Error: No message value received.</div>';
}
$conn = null; // Close the database connection