我有一个Android应用程序,它应根据获得的点数获取用户的当前排名,并在定义的textview“txtRank”中设置它。
这些值存储在MySQL中。当我执行代码时,我总是将rank作为null,但是当我在PHPMYADMIN上执行SQL语句时,它给了我正确的resutl。
有什么想法吗?
这里是PHP:
$uname = $_POST['uname'];
$sql1 = "SET @rownum := 0";
$sql2 = "SELECT rank, points FROM (
SELECT @rownum := @rownum + 1 AS rank, points, uname
FROM points ORDER BY points DESC
) as result WHERE uname=$uname";
mysql_query($sql1);
$result = mysql_query($sql2);
$rows = '';
$data = array();
if (!empty($result))
$rows = mysql_num_rows($result);
else
$rows = '';
if (!empty($rows)){
while ($rows = mysql_fetch_assoc($result)){
$data[] = $rows;
}
}
if ($sql2){
$response["success"] = 1;
$response["user"]["rank"] = $data[0]['rank'];
echo json_encode($response);
}else{
$response["error"] = 2;
$response["error_msg"] = "Something went wrong";
echo json_encode($response);
}
这里是AsynchTask和setText方法:
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_RANK = "rank";
....
private class GetRank extends
AsyncTask<String, String, JSONObject> {
String uname;
@Override
protected void onPreExecute() {
super.onPreExecute();
DatabaseHandler db = new DatabaseHandler(getActivity());
// Hashmap to load data from the Sqlite database
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();
uname = user.get("uname");
}
@Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getUserdata(uname);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if (Integer.parseInt(res) == 1) {
JSONObject json_user = json.getJSONObject("user");
setTextRank(json_user.getString(KEY_RANK));
} else if (Integer.parseInt(red) == 1) {
Toast toast = Toast.makeText(getActivity(),
"Noch kein Bild!", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER
| Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else {
Toast.makeText(getActivity(),
"Fehler aufgetreten, bitte nochmal versuchen",
Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void setTextRank(String text) {
TextView textView = (TextView) getView().findViewById(R.id.txtRank);
textView.setText(text);
}
答案 0 :(得分:0)
您没有将变量正确传递给sql。
你应该连接字符串,例如:
$rownum =mysql_query($sql1);
$sql2 = "SELECT rank, points FROM (
SELECT @rownum := @rownum + 1 AS rank, points, uname
FROM points ORDER BY points DESC
) as result WHERE uname=".$uname;
(我不确定rownum的语法是否有效)。 但是,这不是安全的方式。