//-------------- Chat server BY Kilvish ------------
<?php
// Establish MySQL database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chatdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve chat messages from the database
function getChatMessages() {
global $conn;
$sql = "SELECT * FROM chat_messages ORDER BY created_at ASC";
$result = $conn->query($sql);
$messages = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$messages[] = $row;
}
}
return $messages;
}
// Insert a new chat message into the database
function insertChatMessage($username, $message) {
global $conn;
$sql = "INSERT INTO chat_messages (username, message,created_at) VALUES ('$username', '$message','')";
if ($conn->query($sql) === true) {
return true;
} else {
return false;
}
}
// Handle new chat message submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['username']) && isset($_POST['message'])) {
$username = $_POST['username'];
// $_SESSION[$username]=$uid;
$message = $_POST['message'];
if (insertChatMessage($username, $message)) {
echo "Message sent successfully.";
} else {
echo "Error sending message.";
}
}
// Retrieve chat messages
$chatMessages = getChatMessages();
?>
<!DOCTYPE html>
<html>
<head>
<title>Chat Server</title>
</head>
<body>
<h2>Chat Messages</h2>
<ul>
<?php foreach ($chatMessages as $message): ?>
<li><?php echo $message['username'] . ": " . $message['message']; ?></li>
<?php endforeach; ?>
</ul>
<h2>Send Message</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username:</label>
<input type="text" name="username" required><br><br>
<label for="message">Message:</label>
<input type="text" name="message" required><br><br>
<input type="submit" value="Send">
</form>
</body>
</html>
<?php
// Close the database connection
$conn->close();
?>
Comments
Post a Comment