我是编程新手,请原谅我的问题。我目前正在从远程服务器获取列officer_name。将其解析为 JSON 并发送到应用程序。但我想添加另一个具有 INT 数据类型的列数据 reference 并将其与 officer_name 一起发送到应用程序。我怎样才能实现这样的目标?
sql查询
$sql = "select officer_name from user_tbl where user_name like '".$user_name."' and password like '".$password."' and activate = 1;";
$result = mysqli_query($con,$sql);
$response = array();
if (mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_row($result);
$officer_name = $row[0];
$code = "Login_Success";
array_push($response,array("code"=>$code,"officer_name"=>$officer_name));
echo json_encode($response);
获取 JSON 的 Android Java 代码
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if (code.equals("Login_Failed"))
{
builder.setTitle("Login Error");
displayAlert(jsonObject.getString("message"));
}
else
{
Intent intent = new Intent(Login.this,MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("officer_name", jsonObject.getString("officer_name"));
intent.putExtras(bundle);
startActivity(intent);
}
到目前为止,我只能从服务器获取officer_name。我想从我的数据库添加一个具有 INT 值的数据引用列。
最佳答案
看起来是这样,因为您仅选择 OFFICER_NAME 而没有其他列。 当您想选择更多时,只需输入(SELECTOfficer_name、data_u_want2、data_u_need3 FROM 等..)
我获取用户数据的脚本通常如下所示:
$username = $_POST["username"];
// SELECT what you want
$statement = mysqli_prepare($con,"SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement,"s",$username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement,
$userID,
$username,
$password,
$email,
$age,
$realname,
$streetname,
$postcode,
$city,
$state);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["username"] = $username;
$response["password"] = $password;
$response["email"] = $email;
$response["age"] = $age;
$response["realname"] = $realname;
$response["streetname"] = $streetname;
$response["postcode"] = $postcode;
$response["city"] = $city;
$response["state"] = $state;
}
echo json_encode($response);
您将来应该使用准备好的语句来防止 sql 注入(inject)。
您可以将 $username 更改为 $officer_name 或其他名称,并将您想要的列放入 $response
关于java - 来自服务器的 JSON 数组获取两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130942/