I have a message system. When storing a message in the database, it should store normally and display normally. For example, “What’s Up?” -> “What’s Up?”. However, it stores and displays as “What’s Up” with a backlash after the “t”. How can I fix this so that the message is sent and displayed normally, as it is supposed to.
Here’s my code currently:
<div id="chatSection" class="consult-window-section" style="display: none;">
<?php
// Load chat messages
$chatQuery = "SELECT * FROM consultation_chat
WHERE consultation_id = $consultation_id
ORDER BY sent_at ASC";
$chatResult = mysqli_query($connection, $chatQuery);
?>
<div class="chat-box">
<div class="chat-messages" id="chatMessages">
<?php while ($chat = mysqli_fetch_assoc($chatResult)): ?>
<div class="chat-message <?= $chat['sender_id'] == $_SESSION['id'] ? 'sent' : 'received' ?>">
<p><?= htmlspecialchars(stripslashes($chat['message']), ENT_QUOTES) ?></p>
<span class="timestamp"><?= date("H:i", strtotime($chat['sent_at'])) ?></span>
</div>
<?php endwhile; ?>
</div>
<form method="POST" class="chat-form" id="chatForm">
<input type="hidden" name="consultation_id" value="<?= $consultation_id ?>">
<input type="hidden" name="sender_id" value="<?= $_SESSION['id'] ?>">
<input type="hidden" name="receiver_id" value="<?= $consultant['id'] ?>">
<input type="text" name="message" placeholder="Type your message..." required autocomplete="off">
<button type="submit">Send</button>
</form>
</div>
if (isset($_GET['fetchMessages']) && isset($_GET['consultation_id'])) {
$consultation_id = intval($_GET['consultation_id']);
$user_id = $_SESSION['id'];
$query = "SELECT * FROM consultation_chat WHERE consultation_id = ? ORDER BY sent_at ASC";
$stmt = $connection->prepare($query);
$stmt->bind_param("i", $consultation_id);
$stmt->execute();
$result = $stmt->get_result();
while ($msg = $result->fetch_assoc()) {
$isSender = $msg['sender_id'] === $user_id;
$align = $isSender ? 'right' : 'left';
$color = $isSender ? '#d2bca9' : '#e3d2c3';
echo "<div style='text-align: $align; margin: 10px 0;'>
<div style='display: inline-block; background: $color; padding: 10px 15px; border-radius: 10px; max-width: 70%;'>
<p style='margin: 0; font-size: 16px; font-family: Lora;'>{$msg['message']}</p>
<small style='font-size: 12px; color: gray;'>{$msg['sent_at']}</small>
</div>
</div>";
}
exit;
}
// Handle new message POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
$msg = mysqli_real_escape_string($connection, $_POST['message']);
$sender_id = intval($_POST['sender_id']);
$receiver_id = intval($_POST['receiver_id']);
$consult_id = intval($_POST['consultation_id']);
$stmt = $connection->prepare("INSERT INTO consultation_chat (consultation_id, sender_id, receiver_id, message) VALUES (?, ?, ?, ?)");
$stmt->bind_param("iiis", $consult_id, $sender_id, $receiver_id, $msg);
$stmt->execute();
header("Location: user_window.php?consultation_id=$consult_id§ion=chat");
}