【发布时间】:2019-11-17 10:51:15
【问题描述】:
我想对存储在远程数据库中的 android 应用程序的表进行自定义选择查询。 以下是我的 php 文件,它从 POST 方法中获取 tablename, fields 和 condition 并进行选择查询。然后它返回获取的行的 json 对象。
<?php
require("config.php");
$tablename=$_POST['tablename'];
$condition=$_POST['condition'];
$data=json_decode($_POST['fields']);
$fields = implode(",",$data );
$sql="SELECT $fields FROM $tablename WHERE $condition";
if($res=mysqli_query($con,$sql))
{
while ( $row = $res->fetch_object()) { $myArray[ ] = $row; }
echo json_encode($myArray, JSON_FORCE_OBJECT);
}
else echo json_encode($sql." ".mysqli_error($con));
mysqli_close($con);
?>
我正在使用 POST 方法从我的 android 应用程序发送一个 json 对象请求,如下所示:
// Parameter Values:
String tablename = "teachers";
JSONArray fields = new JSONArray().put("password");
String condition = "teacher_id like \'" + id + "\'";
Map<String,String> params=new HashMap<>();
params.put("tablename",tablename);
params.put("fields",fields.toString());
params.put("condition",condition);
JSONObject jsonRequest = new JSONObject(params);
Toast.makeText(context, jsonRequest.toString(), Toast.LENGTH_SHORT).show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, DOMAIN+"/select.php", jsonRequest, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(context, "Success "+ response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Toast.makeText(context, "Error"+error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
json 对象的格式正确,如下所示:
但我仍然收到此错误:
谁能帮我获取select查询输出的json对象?
更新:
我更新了 php 和 java 文件以使用 POST 而不是 GET。还是一样的错误。
更新:
我提出了打印正确结果的 curl 请求
<?php
//The url you wish to send the POST request to
$url = "*****";
//The data you want to send via POST
$fields = [
'tablename' => 'teachers',
'fields' => '["password"]',
'condition' => 'teacher_id like \'MCA01\''
];
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
echo $result;
?>
输出: {"0":{"密码":"3438735f791**********************8e7e5d24a5"}}
为什么来自android的请求不起作用?
【问题讨论】:
-
您的代码易受 SQL 注入攻击。
-
您能详细说明或推荐任何修复方法吗?
-
我已经更新了代码。有一些进展。我认为问题在于字段变量中的转义序列
-
尽管如此,通过 Internet 将 SQL 发送到 PHP 是一个糟糕的主意。任何人都可以发送他们想要的任何东西。