将变量传递给php文件

时间:2018-09-12 13:00:26

标签: php android sql mysqli

我们尝试从Android应用中的服务器获取数据。对于获取查询,用户应能够根据过滤的数据选择条件。尽管输入的值正确地传递到了表中,但是以某种方式尝试时,最终还是没有输出。 当我们尝试使用变量的固定值进行操作时,一切正常,仅使用变量不起作用,但为什么不呢?这样不可能吗? 我们也被告知,代码不是安全的,但是无论如何都可以正常工作,所以谢谢!!

<?php
$con = new mysqli($server, $user, $password, $db);

if(isset($_POST['number'])){
 $query = "INSERT INTO Table (number) VALUES ('$_POST[number]')";
}

$var = $_POST['number'];
 $query = "SELECT * FROM Table WHERE number = '$var'";
    
    $result = mysqli_query($con, $query);
      
    while($row = mysqli_fetch_assoc($result)) {
        $array[] = $row;
        }
       
    header('Content-Type:Application/json');
    echo json_encode($array);
    mysqli_close($con);  
?>

我们使用的代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GetData();
                InsertData(TempName);
                JSON_DATA_WEB_CALL();
            }
        });
    }
    public void GetData() {
        TempName = name.getText().toString();
    }
    public void InsertData(final String a) {
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
                String NameHolder = a;
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("name", NameHolder));
                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(ServerURL);
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                } catch (ClientProtocolException e) {
                } catch (IOException e) {
                }
                return "Data Inserted Successfully";
            }
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(a);
    }
    public void JSON_DATA_WEB_CALL() {
        jsonArrayRequest = new JsonArrayRequest(ServerURL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        progressBar.setVisibility(View.GONE);
                        JSON_PARSE_DATA_AFTER_WEBCALL(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
        requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonArrayRequest);
    }
    public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
        for (int i = 0; i < array.length(); i++) {
            GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
            JSONObject json = null;
            
        try {
                json = array.getJSONObject(i);
                GetDataAdapter2.setId(json.getInt(JSON_ID));
                GetDataAdapter2.setName(json.getString(JSON_NAME));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            GetDataAdapter1.add(GetDataAdapter2);
        }
        recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
        recyclerView.setAdapter(recyclerViewadapter);
    }
}

2 个答案:

答案 0 :(得分:1)

首先,在您的php文件中,尝试使用

die(var_dump($_POST))

检查您的职位申请是否正确!

这是我的活动代码:

    @Override
    protected List<MyModel> doInBackground(Void... params) {

        Logger.log(Logger.INFO, "DOWNLOAD STARTED!");

        try {
            //I have a Service Class called ConnectionService, that do the verifications and conenction!
            if (connectionService.isConnected && connectionService.hasInternet) {
                //Creating my json to send via POST to my wbs in php.
                JSONObject data = new JSONObject();
                data.put("my_attribute", "AttributeTest");
                JSONObject newData = new JSONObject().accumulate("data", data);
                return connectionService.downloadInfo(newData);
            }
            return null;
        } catch (Exception e) {
            Message.showLongMessage(getApplicationContext(), getString(R.string.error_no_connection));
            Logger.log(Logger.ERROR, e.getMessage());
        }
        return null;
    }

这是我的ConnectionService类:

public List downloadInfo(JSONObject dataJson) {
    try {
        return checkDownloadConnection(connectPost(dataJson));
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        Logger.log(Logger.ERROR, e.getMessage());
    }
    return null;
}

private JSONObject connectPost(JSONObject dataJson) {

    JSONObject jsonObject = null;
    HttpURLConnection connection = null;

    try {
        connection = (HttpURLConnection) new URL("my_url_to_my_php_file").openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestMethod("POST");
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);

        OutputStream os = connection.getOutputStream();
        os.write(dataJson.toString().getBytes("UTF-8"));
        os.flush();

        if (connection.getResponseCode() == 200) {
            jsonObject = new JSONObject(Utils.bytesToString(connection.getInputStream()));
        }

    } catch (IOException | JSONException e) {
        e.printStackTrace();
        Logger.log(Logger.ERROR, e.getMessage());
    }

    if (connection != null) {
        connection.disconnect();
    }
    return jsonObject;
}

public List checkDownloadConnection(JSONObject connectionJson) throws JSONException, IOException {
    if (connection == null) {
        return null;
    }
    //connectionJson will return a result from my php json_encode(die(var_dump($obj)))
    //with status and data "$result = ['status' => true/false, 'message' => 'my message if occur some error', 'data' => $myData];
    String status = String.valueOf(connectionJson.getString("status"));
    if (status.equals(STATUS_FALSE)) {
        Logger.log(Logger.ERROR, String.valueOf(connectionJson.getString("message")));
        return null;
    }

    return hydrateObjects(connectionJson.getJSONArray("data"));
    //this is another function, that i hydrate my info downloaded, you won't need it for your logic.
}

我的Utils.bytesToString函数:

public static String bytesToString(InputStream is) throws IOException {
    byte[] buf = new byte[1024];
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int bytesRead;
    while ((bytesRead = is.read(buf)) != -1) {
        buffer.write(buf, 0, bytesRead);
    }
    String out = new String(buffer.toByteArray());
    return out;
}

希望您能理解。 :)

答案 1 :(得分:0)

您的变量$ _POST [number]未正确发布。

尝试以下教程将数据从android应用发布到PHP代码。

https://www.androidcode.ninja/android-http-client/

希望它对您有用。