从php检索并检查答案

时间:2013-12-03 09:44:58

标签: php android

这是我的PHP代码:
    

class joinTeam
{
//when player joins a team
function join()
{
    if((isset($_POST["userID"]) && !is_null($_POST["userID"])) && (isset($_POST["teamID"]) && !is_null($_POST["teamID"])))
    {
        $teamID = ($_POST["teamID"]);
        $userID = ($_POST["userID"]);
        $cEntry = "";
        $insertTime = "";
        //connect database
        $link_id = db_connect();
        if(!$link_id)
        {
            //database error
            sendResponse(400, 'Invalid Request');
            return false;
        }
        //unicode data in database
        mysql_set_charset("utf8");
        //select player  teamID and userID
        $query = " SELECT c_user_id";
        $query .= "     , c_team_id";
        $query .= "  FROM member_status";
        $query .= " WHERE c_team_id='".$teamID."'";
        $query .= "   AND c_user_id='".$userID."'";
        $result = mysql_query($query);
        $totalRowsCount = mysql_num_rows($result);
        //when player does not exists
        if($totalRowsCount == 0)
        {
            //insert player request
            $query = "  INSERT INTO member_status";
            $query .= "        (c_team_id";
            $query .= "        ,c_user_id";
            $query .= "        ,c_entry";
            $query .= "        ,dt_insert_time";
            $query .= "        )";
            $query .= " VALUES ('".$teamID."'";
            $query .= "        ,'".$userID."'";
            $query .= "        ,'2'";
            $query .= "        ,'".date('Y-m-d H:i:s')."'";
            $query .= "        )";
            $result1 = mysql_query($query);
            if(!$result1)
            {
                sendResponse(400, 'Insert Fail');
                return true;
            }
            else
            {
                $returnData = array(
                    "response" => "Insert Successfull"
                );
                sendResponse(200, json_encode($returnData));
                return true;
            }
        }
        else
        {
            //select last player status
            $query = "   SELECT c_user_id";
            $query .= "       , c_team_id";
            $query .= "       , c_entry";
            $query .= "       , dt_insert_time";
            $query .= "    FROM member_status";
            $query .= "   WHERE c_team_id='".$teamID."'";
            $query .= "     AND c_user_id='".$userID."'";
            $query .= "ORDER BY member_status.dt_insert_time DESC";
            $query .= "   Limit 1";
            $result2 = mysql_query($query);
            while($row = mysql_fetch_array( $result2))
            {
                $cEntry = $row["c_entry"];
                $teamID = $row["c_team_id"];
                $userID = $row["c_user_id"];
                $insertTime = $row["dt_insert_time"];
            }
            switch($cEntry)
            {
                case "1":
                    sendResponse(400, 'Already Registered');
                    return true;
                    break;
                case "2":
                    sendResponse(400, 'Already Requested');
                    return true;
                    break;
                case "3":
                    sendResponse(400, 'Got Request From Team');
                    return true;
                    break;
                case "4":
                    //player request send back
                    $query = " UPDATE member_status";
                    $query .= "   SET c_entry='2'";
                    $query .= " WHERE c_user_id='".$userID."'";
                    $query .= "   AND c_team_id='".$teamID."'";
                    $query .= "   AND dt_insert_time='".$insertTime."'";
                    $result3 = mysql_query($query);
                    if(!$result3)
                    {
                        sendResponse(400, 'Insert Fail');
                        return true;
                    }
                    else
                    {
                        $returnData = array(
                            "response" => "Update Successfull"
                        );
                        sendResponse(200, json_encode($returnData));
                        return true;
                    }
                    break;
                default:
                    //insert new player request
                    $query = "  INSERT INTO member_status";
                    $query .= "        (c_team_id";
                    $query .= "        ,c_user_id";
                    $query .= "        ,c_entry";
                    $query .= "        ,dt_insert_time";
                    $query .= "        )";
                    $query .= " VALUES ('".$teamID."'";
                    $query .= "        ,'".$userID."'";
                    $query .= "        ,'2'";
                    $query .= "        ,'".date('Y-m-d H:i:s')."'";
                    $query .= "        )";
                    $result4 = mysql_query($query);
                    if(!$result4)
                    {
                        sendResponse(400, 'Insert Fail');
                        return true;
                    }
                    else
                    {
                        $returnData = array(
                            "response" => "Insert Successfull"
                        );
                        sendResponse(200, json_encode($returnData));
                        return true;
                    }
            }
        }
    }
    else
    {
        sendResponse(400, 'Invalid Request');
        return true;
    }
}
}
//create object
$joinTeam = new joinTeam;
//call method
$joinTeam -> join();
?>

这是我运行这个php时的结果 1.注册成功后,php就这样回归 {“response”:“插入成功”} 我需要显示“成功注册”

2.但是在已经注册的情况下,php会像那样返回 已被请求。我需要显示“你已经请求”

但我不知道如何检查从php返回

这是我的javaCode:     public void OnClickForSave(View v)抛出异常{

    String result=null;
    String response=null;
    String memberID="000000011";
    String teamID="000008";
    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(2);
    postParameters.add(new BasicNameValuePair("teamID",teamID));
    postParameters.add(new BasicNameValuePair("userID",memberID));


    if(v.getId()==(R.id.imgbtn_layout2))
    {
        Intent intent = new Intent(this, IntentTesting.class);
        startActivity(intent);

    }

    if(v.getId()==(R.id.imgbtn_lsave)){
    if(txt_teamID.getText().toString().trim().equals(null)||txt_teamID.getText().toString().trim().equals(""))
    {
        AlertDialog empty=createDialogEmpty(this,"Enter Team ID");
        empty.show();
        txt_teamID.selectAll();
        txt_teamID.requestFocus();
    }

    else if(txt_teamID.getText().toString().trim().length()>6)
    {
        AlertDialog notFormat=createDialogEmpty(this,"More Than 6 Characters");
        txt_teamID.selectAll();
        txt_teamID.requestFocus();
        notFormat.show();
    }
    else
    {
        try {
            response=CustomHttpClient.executeHttpPost("http://10.0.2.2/football365/joinTeam.php",postParameters);
            //JSONObject jArray = new JSONObject (response);
            //Log.i("JSON",jArray+"");


        } catch (JSONException e) {

            e.printStackTrace();
        }

        result=response.toString();

        checkMessage(response.toString());
        Log.i("JSON",result+"");

    }
}
}

事实是我不知道如何检索

2 个答案:

答案 0 :(得分:0)

我希望这会奏效......

                try {
                    JSONObject json = new JSONObject(response);
                    String str = json.getString("string_name");
                    // Toast this String
                } catch (JSONException e) {

                    e.printStackTrace();
                }

答案 1 :(得分:0)

在您的SQL语句中,在insert语句的末尾,您应该放置SELECT 'InsertSuccessfull' AS Response。然后,在返回结果的PHP文件中,将此while循环将SQL结果编码为JSON格式:

while($e=mysql_fetch_assoc($q)) /*where $q is mysql_query()*/

          $output[]=$e;

       print(json_encode($output));

您将收到[{Response:'InsertSuccessfull'}]之类的回复。现在,您可以在应用中检索此内容:

                String[] listOfResponses = {};
                InputStream is = null;

                String result = "";

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                //http post
                try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("www.mywebservice.com/getAll.php");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();
                }catch(Exception e){
                        Log.e("log_tag", "Error in http connection "+e.toString());
                }
                //convert response to string
                try{
                        //BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                        }
                        is.close();
                        result=sb.toString();
                }catch(Exception e){
                        Log.e("log_tag", "Error converting result "+e.toString());
                }
                //parse json data
                try{
                        JSONArray jArray = new JSONArray(result);

                        for(int i=0;i<jArray.length();i++){
                                JSONObject json_data = jArray.getJSONObject(i);

                                // ATTENTION: 
                                listOfResponses[i] = json_data.getString("Response"); 
                        }

                }catch(JSONException e){
                        Log.e("log_tag", "Error parsing data "+e.toString());
                }

我想我没有遗漏任何东西,但请注意。