Android : JSON get highscore of specific user

on Wednesday, March 25, 2015


I want to display in my app a score for each user, this score is the result of all actions, they will get 2 points for commenting on topics etc.


I created in my database a new table "users" with 2 rows, number and username. This is the php file to add the score and the username: See live



<?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
}

?>


Code to display usernames and scores in JSON: See live



<?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));
}

?>


How can I get ONLY the score of a specific user? Each user should see his individual score in his profile.


0 comments:

Post a Comment