-
Notifications
You must be signed in to change notification settings - Fork 0
/
rooms.php
38 lines (34 loc) · 1.35 KB
/
rooms.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
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept");
header('Content-Type: application/json');
$pdo = new PDO('mysql:host=localhost;dbname=ag_chat', 'root', 'koodinh');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = file_get_contents('php://input');
$data = json_decode($data, true);
//chèn dữ liệu vào bảng tin nhắn
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$stm = $pdo->prepare('INSERT INTO msgs(content,username,created_date) VALUES (?,?,?)');
$stm->execute(array($data['content'], $data['username'], time()));
//code...
} catch (\Throwable $th) {
//throw $th;
echo $th->getMessage();
}
echo json_encode(array('content' => $data['content'], 'username' => $data));
}
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$lastTime = $_GET['lastTime'];
if ($lastTime == null || $lastTime == '') {
$result = $pdo->query('SELECT * FROM msgs ORDER BY created_date DESC LIMIT 0,5');
} else {
$result = $pdo->query('SELECT * FROM msgs WHERE created_date > ' . $lastTime . ' ORDER BY created_date DESC');
}
$data = array();
foreach ($result as $r) {
$data[] = $r;
}
echo json_encode($data);
}