-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstartconversation copy.php
66 lines (55 loc) · 1.96 KB
/
startconversation copy.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
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
<?php
include 'header.php';
// Establish the database connection
$conn = new mysqli("$servernamesql", "$usernamesql", "$passwordsql", "$databasesql");
// Check the database connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Assuming you have already established a database connection
// Get the sender ID, recipient username, and message content from the request
$senderId = $_SESSION['userid']; // Assuming you have the sender ID stored in the session
$recipientUsername = $_POST['recipient']; // Assuming it is passed as a POST parameter
// Get the recipient ID based on the recipient username
$query = "SELECT users.userid, conversations.sender_id, conversations.recipient_id
FROM users
LEFT JOIN conversations ON users.userid = conversations.sender_id
WHERE users.username = ? LIMIT 1;";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $recipientUsername);
$stmt->execute();
$result = $stmt->get_result();
// Check if the recipient exists
if ($result->num_rows > 0 && $result->num_rows <= 1) {
// Fetch the recipient ID
$row = $result->fetch_assoc();
$recipientId = $row['userid'];
// Insert the message into the database
$query = "INSERT INTO conversations (sender_id, recipient_id) VALUES (?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param('ii', $senderId, $recipientId);
$stmt->execute();
// Check if the message was inserted successfully
if ($stmt->affected_rows > 0) {
$response = array(
'success' => true
);
} else {
$response = array(
'success' => false
);
}
} else {
// Recipient does not exist
$response = array(
'success' => false
);
}
// Close the database connection
$stmt->close();
$conn->close();
// Set the response header to JSON
header('Content-Type: application/json');
// Send the JSON response
echo json_encode($response);
?>