-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsubmit_message.php
More file actions
69 lines (58 loc) · 1.94 KB
/
submit_message.php
File metadata and controls
69 lines (58 loc) · 1.94 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
// Start session
session_start();
// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
// Database connection
$db_file = realpath(dirname(__FILE__) . '/users.db');
try {
$conn = new PDO("sqlite:$db_file");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Create messages table if it doesn't exist
$sql = "CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
$conn->exec($sql);
// Retrieve user data from the database
$user_id = $_SESSION['user_id'];
$sql = "SELECT username FROM users WHERE id = :user_id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
$username = $row["username"];
} else {
// Handle error
$error = "Error retrieving user data.";
}
// Insert message into the database
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message = $_POST["message"];
$sql = "INSERT INTO messages (user_id, username, message) VALUES (:user_id, :username, :message)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':message', $message, PDO::PARAM_STR);
$stmt->execute();
// Redirect back to the dashboard with success message
header("Location: dashboard.php?success=true");
exit();
}
} catch (PDOException $e) {
// Handle database connection error
$error = "Database error: " . $e->getMessage();
}
// Close the database connection
$conn = null;
// Redirect back to the dashboard
header("Location: dashboard.php");
exit();
?>