-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrecent.php
81 lines (71 loc) · 1.96 KB
/
recent.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
// Enlai Li 261068637
// make sure database exists
require_once "database_create.php";
// db info
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// check if the request is correct
if ($_SERVER['REQUEST_METHOD'] !== 'GET' || !isset($_GET['sort']) || !isset($_GET['page'])) {
http_response_code(400); // Bad Request
exit();
}
try {
$mysqli = new mysqli($servername, $username, $password);
if ($mysqli->connect_error) {
throw new Exception($mysqli->connect_error);
}
$mysqli->select_db($dbname);
// // Debug
// $sort = "recent";
// $page = 2;
// get sorting method
$sort = $_GET['sort'] ?? "recent";
// get current page
$page = intval($_GET['page']) ?? 1;
// get search
$search = $_GET['search'] ?? "";
// determine sorting method
switch ($sort) {
case 'popular':
$order_by = "visits DESC, number DESC";
break;
case 'oldest':
$order_by = "number ASC";
break;
case 'recent':
default:
$order_by = "number DESC";
break;
}
// determine from where to start
$items_per_page = 10;
$start_from = ($page - 1) * $items_per_page;
// get submissions in a particular order
$result = $mysqli->execute_query(
"SELECT date, id, content, visits
FROM user_content
WHERE content LIKE ?
ORDER BY $order_by
LIMIT ? OFFSET ?",
["%" . $search . "%", $items_per_page + 1, $start_from]
);
$rows = $result->fetch_all();
// check if next page exists
if (sizeof($rows) <= $items_per_page) {
$has_next_page = false;
} else {
$has_next_page = true;
}
$entries = array_slice($rows, 0, $items_per_page);
echo json_encode([
"entries" => $entries,
"has_next_page" => $has_next_page
]);
} catch (Exception $e) {
echo $e->getMessage();
} finally {
$mysqli->close();
}