我希望在我的应用中显示每个用户的分数,这个分数是所有操作的结果,他们将获得2分来评论主题等。
我在我的数据库中创建了一个新表"用户"有2行,数字和用户名。 这是用于添加分数和用户名的php文件:
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
if (!empty($_POST)) {
//initial query
$query = "INSERT INTO users ( score, username ) VALUES ( :nu, :user) ";
//Update query
$query_params = array(
':nu' => $_POST['score'],
':user' => $_POST['username']
);
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't add post!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);
} else {
?>
<h1>Add Score</h1>
<form action="addscore.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="post username" />
<br /><br />
Score:<br />
<input type="text" name="score" placeholder="post score" />
<br /><br />
<input type="submit" value="Add Score" />
</form>
<?php
}
?>
以JSON显示用户名和分数的代码:
<?php
/*
Our "config.inc.php" file connects to database every time we include or require
it within a php script. Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("config.inc.php");
//initial query
$query = "Select * FROM users";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response = array();
foreach ($rows as $row) {
$post = array();
$post["score"] = $row["score"];
$post["username"] = $row["username"];
//update our repsonse JSON data
array_push($response, $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
如何才能获得特定用户的分数? 每个用户都应该在他的个人资料中看到他的个人得分。
答案 0 :(得分:0)
您可以从
更改您的查询Select * FROM users
到
Select * FROM users where id = '1'