AI chatbots are becoming a practical feature for websites, customer portals, internal tools, and online services. With PHP handling the application logic, MySQL storing conversations, and an AI provider generating responses, you can build a chatbot that is both useful and maintainable without adopting an entirely new technology stack.
This guide explains how to build an AI chatbot with PHP and MySQL from the ground up. You will create a simple chat interface, design a database for conversations and messages, send user prompts to an AI API, save the response, and return the result to the browser. You will also learn how to improve the basic implementation with authentication, validation, rate limiting, security controls, context management, and production monitoring.
The examples use modern PHP with PDO and cURL. The API request format is compatible with many chat-completion services, but each provider may use different endpoint URLs, model names, authentication requirements, and response fields. Check your provider's current documentation before deploying.
What You Will Build
By the end of the tutorial, you will have a chatbot with the following flow:
- A visitor submits a message through a web form.
- PHP validates the request and identifies the conversation.
- The application loads relevant conversation history from MySQL.
- PHP sends a structured request to an AI service.
- The AI response is saved in MySQL.
- The response is returned to the browser and displayed in the chat window.
The design deliberately separates the user interface, application logic, database access, and AI integration. This makes it easier to replace the frontend, change providers, add authentication, or introduce features such as document search later.
How the Architecture Works
A basic PHP and MySQL AI chatbot can be organized into four layers:
- Frontend: An HTML page and JavaScript code that display messages and send requests to the server.
- Application layer: PHP endpoints that validate input, manage sessions, enforce permissions, and coordinate the conversation.
- Data layer: MySQL tables that store users, conversations, messages, and operational metadata.
- AI integration layer: A small PHP service that sends messages to an external AI provider and parses the result.
The browser should communicate with your PHP application rather than directly with the AI provider. Keeping the API request on the server protects your secret key, gives you control over validation and rate limits, and allows you to save a reliable record of every interaction.
Prerequisites
Before starting, prepare the following:
- PHP 8.1 or a later supported version.
- MySQL or MariaDB.
- PDO with the MySQL driver enabled.
- The cURL PHP extension enabled.
- A web server such as Apache or Nginx, or PHP's built-in development server.
- An API key from the AI provider you intend to use.
- Basic familiarity with HTML, JavaScript, SQL, and PHP.
For local development, you can use a traditional PHP and MySQL installation or a local environment such as Docker, XAMPP, MAMP, or a similar stack. Production deployments should use HTTPS and a protected secrets-management strategy.
Plan the Database
Conversation data should be modeled explicitly rather than stored as one large text field. A relational design makes it easier to display message history, delete a conversation, audit activity, and associate chats with authenticated users.
This example uses three tables:
- users: Optional application users who own conversations.
- conversations: One record for each chat session.
- messages: Individual user and assistant messages belonging to a conversation.
Create the database and tables with the following SQL:
CREATE DATABASE ai_chatbot CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE ai_chatbot;
CREATE TABLE users (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
CREATE TABLE conversations (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT UNSIGNED NULL,
title VARCHAR(255) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT fk_conversations_user
FOREIGN KEY (user_id) REFERENCES users(id)
ON DELETE CASCADE,
INDEX idx_conversations_user_updated (user_id, updated_at)
) ENGINE=InnoDB;
CREATE TABLE messages (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
conversation_id BIGINT UNSIGNED NOT NULL,
role ENUM('system', 'user', 'assistant') NOT NULL,
content MEDIUMTEXT NOT NULL,
provider_message_id VARCHAR(255) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_messages_conversation
FOREIGN KEY (conversation_id) REFERENCES conversations(id)
ON DELETE CASCADE,
INDEX idx_messages_conversation_created (conversation_id, created_at)
) ENGINE=InnoDB;
The MEDIUMTEXT type gives messages more room than a typical VARCHAR, although you should still enforce application-level length limits. The foreign keys ensure that messages cannot remain attached to a deleted conversation.
Why store each message separately?
Storing each message as a row gives you useful flexibility. You can paginate long conversations, calculate usage, search message content, export a conversation, or display messages in chronological order. It also allows you to distinguish user messages from assistant messages without parsing a large JSON document.
If you need to store provider-specific information such as token usage, finish reasons, or moderation results, add dedicated columns or a JSON metadata column. Keep the core message content separate from provider-specific implementation details.
Configure the PHP Application
A small project can begin with a simple directory structure:
chatbot/
├── public/
│ ├── index.php
│ ├── chat.php
│ └── app.js
├── src/
│ ├── Database.php
│ ├── ChatService.php
│ └── helpers.php
├── config/
│ └── bootstrap.php
└── .env
Only the public directory should be directly accessible from the web. Configuration files and source code should remain outside the public web root whenever your hosting setup allows it.
Environment variables
Do not hard-code an AI API key in PHP, JavaScript, HTML, or a public repository. Store it as an environment variable or in a secrets manager. A local environment file might contain values like these:
APP_ENV=local
DB_HOST=127.0.0.1
DB_PORT=3306
DB_NAME=ai_chatbot
DB_USER=chatbot_user
DB_PASSWORD=change_this_password
AI_API_KEY=replace_with_your_secret_key
AI_API_URL=https://api.example.com/v1/chat/completions
AI_MODEL=your-selected-model
The URL and model above are placeholders. Use the endpoint and model required by your selected provider. In production, ensure that your deployment platform injects secrets securely and does not expose them through error pages or source control.
Database connection with PDO
PDO provides prepared statements and a consistent interface for MySQL access. Create a database helper similar to this:
<?php
function database(): PDO
{
static $pdo = null;
if ($pdo instanceof PDO) {
return $pdo;
}
$host = getenv('DB_HOST') ?: '127.0.0.1';
$port = getenv('DB_PORT') ?: '3306';
$name = getenv('DB_NAME') ?: 'ai_chatbot';
$user = getenv('DB_USER') ?: 'chatbot_user';
$password = getenv('DB_PASSWORD') ?: '';
$dsn = "mysql:host={$host};port={$port};dbname={$name};charset=utf8mb4";
$pdo = new PDO($dsn, $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
return $pdo;
}
In a real project, load environment variables through your deployment environment or a well-maintained configuration library. The important principles are to avoid credentials in source code, use UTF-8, disable emulated prepares where appropriate, and make database failures visible in server logs without displaying sensitive details to visitors.
Create a Conversation
A conversation can be created when the user opens a new chat or when the first message arrives. Creating it on the first message avoids empty records. The following function creates a conversation for an authenticated user or for an anonymous session if your application supports guests:
<?php
function createConversation(PDO $pdo, ?int $userId, ?string $title = null): int
{
$statement = $pdo->prepare(
'INSERT INTO conversations (user_id, title) VALUES (:user_id, :title)'
);
$statement->execute([
'user_id' => $userId,
'title' => $title,
]);
return (int) $pdo->lastInsertId();
}
If anonymous chats are allowed, do not rely on an ID supplied by the browser alone. Use a secure server-side session or an unguessable conversation token, and verify ownership before reading or modifying a conversation.
Save and Load Messages
Use prepared statements for every value that originates from a request, cookie, URL, or external service. This prevents SQL injection and makes the database code easier to reason about.
<?php
function saveMessage(
PDO $pdo,
int $conversationId,
string $role,
string $content,
?string $providerMessageId = null
): int {
$allowedRoles = ['system', 'user', 'assistant'];
if (!in_array($role, $allowedRoles, true)) {
throw new InvalidArgumentException('Invalid message role.');
}
$statement = $pdo->prepare(
'INSERT INTO messages
(conversation_id, role, content, provider_message_id)
VALUES
(:conversation_id, :role, :content, :provider_message_id)'
);
$statement->execute([
'conversation_id' => $conversationId,
'role' => $role,
'content' => $content,
'provider_message_id' => $providerMessageId,
]);
return (int) $pdo->lastInsertId();
}
function loadMessages(PDO $pdo, int $conversationId, int $limit = 20): array
{
$limit = max(1, min($limit, 100));
$statement = $pdo->prepare(
"SELECT role, content
FROM messages
WHERE conversation_id = :conversation_id
ORDER BY created_at DESC, id DESC
LIMIT {$limit}"
);
$statement->execute(['conversation_id' => $conversationId]);
$messages = $statement->fetchAll();
return array_reverse($messages);
}
The limit is clamped in PHP before being placed into the SQL string because many database drivers do not handle a bound parameter for a limit consistently. The user-controlled conversation ID remains a bound parameter.
Integrate the AI API
The AI integration should be isolated in its own service. That prevents provider-specific HTTP code from spreading throughout your application and makes future changes easier.
Many conversational AI APIs accept a list of messages with roles such as system, user, and assistant. A generic PHP service can look like this:
<?php
final class ChatService
{
public function __construct(
private readonly string $apiUrl,
private readonly string $apiKey,
private readonly string $model
) {
}
public function reply(array $messages): array
{
$payload = [
'model' => $this->model,
'messages' => $messages,
];
$ch = curl_init($this->apiUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey,
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 60,
]);
$body = curl_exec($ch);
$curlError = curl_error($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($body === false) {
throw new RuntimeException('AI request failed: ' . $curlError);
}
$data = json_decode($body, true);
if ($status < 200 || $status >= 300) {
throw new RuntimeException('AI provider returned HTTP ' . $status);
}
if (!is_array($data)) {
throw new RuntimeException('AI provider returned invalid JSON.');
}
$content = $data['choices'][0]['message']['content'] ?? null;
if (!is_string($content) || trim($content) === '') {
throw new RuntimeException('AI provider returned no message content.');
}
return [
'content' => trim($content),
'provider_message_id' => isset($data['id']) ? (string) $data['id'] : null,
'raw' => $data,
];
}
}
The response path shown here is common but not universal. Some providers use different JSON structures, authentication headers, or request fields. Keep the provider-specific parsing inside this class and write a small adapter when you need to support multiple providers.
Add a system instruction
A system message establishes the chatbot's role and behavioral boundaries. It should describe the assistant's purpose, answer style, limitations, and escalation behavior. For example:
$systemMessage = [
'role' => 'system',
'content' => 'You are a helpful support assistant. Answer clearly and briefly. If you are unsure, say so instead of inventing information. Do not request passwords, payment card numbers, or other secrets.',
];
System instructions are not a replacement for application security. A prompt cannot enforce authorization, prevent data leaks, or guarantee that the model will follow every rule. Sensitive actions must be controlled by PHP code and server-side permissions.
Build the Chat Endpoint
The endpoint is responsible for accepting a message, checking the conversation, loading context, calling the AI service, and saving the result. A simplified chat.php endpoint could look like this:
<?php
require_once __DIR__ . '/../src/Database.php';
require_once __DIR__ . '/../src/ChatService.php';
header('Content-Type: application/json; charset=utf-8');
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
$message = trim((string) ($input['message'] ?? ''));
$conversationId = isset($input['conversation_id'])
? (int) $input['conversation_id']
: null;
if ($message === '') {
throw new InvalidArgumentException('Message cannot be empty.');
}
if (mb_strlen($message) > 4000) {
throw new InvalidArgumentException('Message is too long.');
}
$pdo = database();
$userId = $_SESSION['user_id'] ?? null;
if ($conversationId === null) {
$conversationId = createConversation($pdo, $userId);
}
$conversationCheck = $pdo->prepare(
'SELECT id FROM conversations
WHERE id = :id AND (user_id = :user_id OR :user_id IS NULL)'
);
$conversationCheck->execute([
'id' => $conversationId,
'user_id' => $userId,
]);
if (!$conversationCheck->fetch()) {
http_response_code(404);
echo json_encode(['error' => 'Conversation not found.']);
exit;
}
saveMessage($pdo, $conversationId, 'user', $message);
$history = loadMessages($pdo, $conversationId, 20);
$messages = array_merge(
[$systemMessage],
array_map(static function (array $item): array {
return [
'role' => $item['role'],
'content' => $item['content'],
];
}, $history)
);
$service = new ChatService(
getenv('AI_API_URL') ?: '',
getenv('AI_API_KEY') ?: '',
getenv('AI_MODEL') ?: ''
);
$result = $service->reply($messages);
saveMessage(
$pdo,
$conversationId,
'assistant',
$result['content'],
$result['provider_message_id']
);
echo json_encode([
'conversation_id' => $conversationId,
'message' => $result['content'],
], JSON_UNESCAPED_UNICODE);
} catch (InvalidArgumentException $exception) {
http_response_code(422);
echo json_encode(['error' => $exception->getMessage()]);
} catch (Throwable $exception) {
error_log($exception->getMessage());
http_response_code(500);
echo json_encode(['error' => 'The chatbot is temporarily unavailable.']);
}
This is an instructional example rather than a complete framework controller. In a production application, initialize sessions before reading them, implement an ownership query appropriate to your authentication model, add CSRF protection for cookie-based authentication, and avoid returning raw exception messages to visitors.
Important ownership issue
The ownership check must match your application. For authenticated users, compare the conversation's user_id with the current authenticated user. For guest users, use a server-side session token or another access mechanism. Never allow a visitor to retrieve any conversation merely by changing an integer in the request.
Create the Frontend
The frontend can remain simple. The page needs a message container, a text area, and a submit button:
<main class="chat">
<h1>AI Assistant</h1>
<div id="messages" aria-live="polite"></div>
<form id="chat-form">
<label for="message">Message</label>
<textarea id="message" name="message" rows="4" required></textarea>
<button type="submit">Send</button>
</form>
</main>
Use JavaScript to submit JSON to the PHP endpoint and render the result. The example below creates text nodes instead of inserting model output as raw HTML. This is an important defense against cross-site scripting.
const form = document.querySelector('#chat-form');
const input = document.querySelector('#message');
const messages = document.querySelector('#messages');
let conversationId = null;
function addMessage(role, content) {
const element = document.createElement('p');
element.className = `message message-${role}`;
element.textContent = content;
messages.appendChild(element);
messages.scrollTop = messages.scrollHeight;
}
form.addEventListener('submit', async (event) => {
event.preventDefault();
const message = input.value.trim();
if (!message) return;
addMessage('user', message);
input.value = '';
const button = form.querySelector('button');
button.disabled = true;
try {
const response = await fetch('/chat.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
conversation_id: conversationId,
message
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Request failed.');
}
conversationId = data.conversation_id;
addMessage('assistant', data.message);
} catch (error) {
addMessage('error', error.message);
} finally {
button.disabled = false;
input.focus();
}
});
If you want formatted assistant responses, do not pass untrusted model output directly to innerHTML. Convert Markdown through a trusted sanitizer or render a restricted format yourself. Even then, treat model-generated content as untrusted input.
Manage Conversation Context
AI models do not automatically remember previous requests. Your application creates the appearance of memory by sending relevant prior messages with each new request. The simplest method is to load the most recent messages, as shown earlier.
However, sending every message forever creates two problems: requests become larger and costs or latency may increase. It may also exceed the model's context limit. Use one or more of these strategies:
- Send only the most recent messages.
- Summarize older parts of the conversation and store the summary.
- Keep a separate conversation summary column.
- Remove irrelevant greetings and repeated content.
- Set an application-specific maximum number of characters or tokens.
A summary can be stored as a system-style record or in a separate conversation_summaries table. When summarizing, make clear that the summary is untrusted context and verify important facts against authoritative application data.
Do not trust conversation history blindly
Stored messages can contain prompt injection attempts, personal data, or instructions that conflict with current application rules. The server should decide which records are included and what operations the assistant is allowed to perform. Conversation history is context, not authorization.
Make the Chatbot More Useful with Application Data
A general chatbot can answer questions, but it does not automatically know your product catalog, internal procedures, account records, or support policies. To answer questions about your own data, your PHP application should retrieve relevant information and include it as controlled context.
A safe pattern is:
- Classify the user's request.
- Use PHP to query the appropriate database records or service.
- Filter the result according to the authenticated user's permissions.
- Place only the necessary information into the AI request.
- Tell the assistant to answer using the supplied context and acknowledge when it is insufficient.
Do not let a model generate arbitrary SQL and execute it without strict controls. If natural-language database queries are required, use an allowlisted query layer, read-only credentials, schema restrictions, validation, and human review for sensitive operations.
Add Authentication and Authorization
Authentication identifies the person using the application. Authorization determines which conversations and data that person may access. These are separate responsibilities.
For user accounts:
- Store passwords with PHP's
password_hash()function. - Check passwords with
password_verify(). - Regenerate the session ID after login.
- Use secure, HttpOnly, SameSite cookies.
- Require HTTPS in production.
- Check conversation ownership on every read, update, and delete operation.
Do not place a user's full account data into the prompt simply because the user is authenticated. Fetch only the fields needed for the current task, and apply the same access rules that your normal application endpoints use.
Protect the Chatbot
An AI chatbot combines normal web application risks with model-specific risks. Security should be designed before launch rather than added after a misuse incident.
Validate input
Set limits on message length, request size, conversation identifiers, and the number of messages submitted in a period. Reject malformed JSON and unexpected fields. Input validation reduces abuse and prevents your application from processing unnecessarily large requests.
Prevent SQL injection
Use PDO prepared statements. Never concatenate user input into SQL. Table names, sort directions, and other SQL identifiers should come from fixed allowlists rather than direct request values.
Protect against cross-site scripting
Escape user and model output when displaying it. If you support Markdown or HTML, use a well-maintained sanitizer with a restrictive allowlist. Never assume model output is safe merely because it came from an AI provider.
Use CSRF protection
If the application uses cookie-based sessions, protect state-changing requests with CSRF tokens. SameSite cookies help, but they should not be your only defense for sensitive actions.
Keep secrets on the server
Never expose the AI API key in browser JavaScript. A visitor can inspect all frontend code and network requests. The browser should call your backend, and your backend should call the provider.
Limit prompt injection impact
Prompt injection occurs when content attempts to manipulate the assistant into ignoring intended instructions or revealing restricted information. Reduce its impact by keeping authorization outside the model, separating instructions from retrieved data, limiting tools, and refusing to place secrets in prompts.
Moderate where appropriate
Depending on your product, you may need controls for abusive, dangerous, illegal, or privacy-sensitive content. Use the safety features offered by your provider, add application-specific rules, and provide a clear escalation path. Do not promise that automated filtering will catch every unsafe request.
Handle Errors Gracefully
External AI requests can fail because of network timeouts, provider rate limits, invalid credentials, service interruptions, context limits, or malformed responses. Treat these as expected operational conditions.
A good error strategy should:
- Return a short, non-sensitive message to the visitor.
- Log enough information for developers to investigate.
- Use different handling for validation errors, authentication failures, rate limits, and server errors.
- Avoid retrying every failure automatically.
- Prevent duplicate messages when a client retries a request.
For temporary failures, an exponential backoff strategy may help. Use a small maximum retry count and respect provider guidance. Do not retry invalid requests or authentication failures because doing so only adds delay and load.
Prevent duplicate submissions
Users may click the send button more than once or retry after a network interruption. Add a client-generated request ID and store it with the user message, or use a separate idempotency table. Before processing a request, check whether that request ID has already produced a response.
Control Cost and Resource Usage
Each request may consume provider resources and database capacity. Add controls before exposing the chatbot to a large audience:
- Limit the length of each message.
- Limit the number of requests per user and IP address.
- Limit conversation history sent to the provider.
- Use an appropriate model for each task rather than the most capable model for everything.
- Cache answers to carefully selected, non-personal questions.
- Track provider usage when the API makes that information available.
- Set a monthly budget alert or operational spending limit where supported.
Rate limiting can be implemented with a database table, Redis, or a gateway such as a reverse proxy. A database-only solution may be sufficient for a small application, but high-traffic systems usually benefit from an in-memory counter with expiration.
Store Usage and Operational Metadata
Messages are only part of the information useful for operating a chatbot. Consider adding fields such as:
- Request ID.
- Model name.
- Latency in milliseconds.
- Input and output usage, if supplied by the provider.
- HTTP status or error category.
- Moderation result.
- Application version.
Keep personal data and operational data separate where practical. Restrict access to logs because they may contain user questions, account information, or confidential business content.
Improve the User Experience
A functional chatbot can still feel slow or unreliable if the interface does not communicate what is happening. Add the following improvements:
- Show a typing or loading indicator while the request is in progress.
- Disable duplicate submission without preventing the user from canceling.
- Keep the user's message visible immediately.
- Provide a retry action when a request fails.
- Allow the user to start a new conversation.
- Display timestamps or conversation titles when useful.
- Make the interface keyboard accessible.
- Ensure readable contrast and responsive behavior on mobile screens.
For longer responses, streaming can make the interface feel faster because text appears incrementally. Streaming requires a different server and browser flow, such as Server-Sent Events or a streamed fetch response. Implement regular request-and-response behavior first, then add streaming after authentication, cancellation, error handling, and output sanitization are working correctly.
Use Transactions Carefully
A user message and assistant message are logically related, but the AI request occurs outside MySQL. You should not hold a database transaction open while waiting for an external network request because the request may take a long time or fail.
A safer sequence is:
- Validate the request.
- Confirm conversation ownership.
- Save the user message.
- Load the context.
- Call the AI provider without an open database transaction.
- Save the assistant message if the call succeeds.
- Record an error state or event if it fails.
If you need stronger consistency, add message status fields such as pending, completed, and failed. This helps recover from a process crash between saving the user message and saving the response.
Testing the Application
Test the chatbot at several levels instead of relying only on manual conversations.
Unit tests
Test input validation, message formatting, provider response parsing, error classification, and authorization helpers with isolated test data.
Integration tests
Use a test database to verify that conversations and messages are created correctly. Mock the external AI service so tests do not depend on network availability or incur provider charges.
Security tests
Try to access another user's conversation, submit invalid JSON, inject SQL-like values, insert HTML into a message, exceed message limits, reuse CSRF tokens incorrectly, and send requests without authentication. Verify that errors do not disclose secrets or database details.
Operational tests
Test timeouts, provider errors, rate limits, duplicate requests, slow responses, and browser refreshes during a request. Confirm that logs contain useful diagnostic information without storing more personal data than necessary.
Deploy the PHP and MySQL Chatbot
A basic production deployment should include:
- HTTPS with a valid certificate.
- A PHP version receiving security updates.
- A MySQL account with only the permissions the application needs.
- Environment-specific configuration and protected secrets.
- Database backups tested through restoration, not merely scheduled.
- Centralized error monitoring and health checks.
- Log rotation and access controls.
- Configured request, upload, and execution limits.
- A deployment process that can be rolled back.
Configure PHP to avoid displaying detailed errors to visitors in production. Send errors to a protected log and monitor them. Restrict the public web root to files that users actually need to access.
Privacy and Data Retention
Chat conversations may contain personal, confidential, or regulated information. Before launching, decide what you need to store and how long you need to keep it.
Document:
- What information is collected.
- Why conversations are stored.
- Who can access them.
- Whether content is sent to an external AI provider.
- How users can request deletion or export.
- How long backups retain deleted information.
- Whether data is used for evaluation or product improvement.
Delete conversations and related messages through a controlled application operation. Because the schema uses cascading foreign keys, deleting a conversation can remove its messages, but confirm that copies do not remain in logs, backups, analytics systems, or provider-side storage.
Common Mistakes to Avoid
Calling the AI provider from JavaScript
This exposes the API key and removes your ability to enforce server-side controls. Route requests through PHP.
Saving the entire chat as one database field
This makes pagination, searching, deletion, and auditing unnecessarily difficult. Store messages as separate records.
Sending unlimited history
Long conversations increase latency and may exceed context limits. Use a window, summary, or retrieval strategy.
Rendering model output as trusted HTML
Model responses can contain markup or unexpected content. Escape output or sanitize it before rendering.
Allowing the model to enforce permissions
Models generate text; they do not replace application authorization. Enforce permissions in PHP and the database.
Logging everything
Verbose logs can accidentally expose personal data and secrets. Log request IDs, error categories, timing, and safe diagnostic context rather than unrestricted prompt content.
Possible Extensions
Once the basic chatbot is stable, you can add features incrementally:
- User registration and conversation history.
- Conversation search and export.
- Admin review tools.
- Feedback buttons for response quality.
- Streaming responses.
- File uploads with type and size validation.
- Retrieval-augmented generation using indexed documents.
- Tool calls to approved application functions.
- Multilingual interfaces.
- Human handoff to a support team.
For document-based question answering, do not simply place every document in every prompt. Extract and index content, retrieve relevant sections for the current question, enforce document permissions, and include only the selected context. For tool use, expose narrow functions such as get_order_status rather than unrestricted database access.
A Practical Build Checklist
Use this checklist before calling the chatbot ready for production:
- Database tables use foreign keys and useful indexes.
- All database values use prepared statements.
- The API key is stored outside source code and browser code.
- Conversation ownership is checked on every request.
- Input length and request frequency are limited.
- Output is escaped or sanitized before display.
- CSRF protection is enabled where session cookies are used.
- Provider timeouts and failures are handled safely.
- Duplicate submissions are detected or tolerated.
- Conversation context is bounded.
- Logs do not expose secrets or unnecessary personal data.
- Backups and deletion procedures have been tested.
- Monitoring can detect increased errors, latency, and usage.
Conclusion
Building an AI chatbot with PHP and MySQL is primarily an application design task, not just an API call. PHP manages validation, authentication, authorization, business rules, and communication with the AI provider. MySQL provides durable conversation storage and operational history. The AI service generates responses, but your application remains responsible for deciding what data is available, what actions are permitted, and how output is presented.
Start with a small, well-structured implementation: separate messages into relational records, keep the provider integration isolated, use prepared statements, protect secrets, and validate every request. Then add context management, rate limiting, monitoring, privacy controls, and richer features as your product requirements become clear. This approach gives you a chatbot that is easier to secure, test, maintain, and evolve.