我正在尝试从数据库的选定表中填充json数组。 主表包含用户的所有信息,我想从中选择10个具有顶级XP的成员。
我的代码:
window.onload = function () {
var anchors, clicked_count, clicked, i, cur_anchor, my_anchor_id;
anchors = document.getElementsByTagName("a");
clicked_count = 0;
clicked = {};
for (i = 0; i < anchors.length; i++) {
cur_anchor = anchors[i];
cur_anchor.setAttribute("class", i);
cur_anchor.onclick = function (e) {
e = e || window.event;
e.preventDefault();
my_anchor_id = this.getAttribute("class");
if (!(my_anchor_id in clicked)) {
clicked[my_anchor_id] = null;
if (++clicked_count === anchors.length) {
window.location.href = this.getAttribute('href');
}
}
};
}
};
答案 0 :(得分:1)
首先,没有理由检查是否发布了USERNAME
,因为您从未使用过USERNAME
字段。其次,你错过了一个收尾卷曲。
至少,你应该重新排序你的sql语句 - LIMIT
之后使用ORDER BY
$serverName = "MyServerName";
$dbUsername = "DatabaseUsername";
$dbPassword = "DatabasePassword";
$dbName = "DatabaseID";
$tableName = "TableName";
$conn = new mysqli($serverName, $dbUsername, $dbPassword, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
try {
$sqlTopMembers = "SELECT XP, username FROM $tableName ORDER BY XP DESC LIMIT 10";
if (!($result = $conn->query($sql)))
die($conn->error);
if ($result->num_rows) {
$rankings = [];
while ($row = $result->fetch_assoc()) {
$rankings[] = $row;
}
echo json_encode(array($tableName => $rankings));
}
} catch (Exception $e) {
echo "Error ", $e->getMessage();
}
答案 1 :(得分:0)
改变这个:
while ($row = $result->fetch_assoc()) {
$rankings[$i] = $row;
$i++;
}
echo json_encode(array($tableName => $rankings));
进入这个:
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$rankings[$i] = $row;
$i++;
}
echo json_encode($rankings);