所以我有一个代码块,在数据库中查找用户名,所以我不会有重复项。 问题是即使有一个名为“swane”的用户名,它也说没有这样的东西。 这是java调用:
params.put("name", "swane");
JSONObject json = jsonParser.makeHttpRequest(urlNameLookup, "POST", params);
这是解析器:
package com.example.denis.onthego;
import android.content.ContentValues;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class JSONParser {
static JSONObject jObj;
static String json;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public static JSONObject makeHttpRequest(String url, String method, ContentValues params) {
// Making HTTP request
try {
final OkHttpClient client = new OkHttpClient();
Request request;
// check for request method
if (method.equals("POST")) {
// request method is POST
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
String content = "";
for (String key : params.keySet())
{
if ( !content.isEmpty())
content += "&";
content += key + "=" + params.get(key);
}
RequestBody body = RequestBody.create(contentType, content);
request = new Request.Builder().url(url).post(body).build();
}
else {
// request method is GET
request = new Request.Builder().url(url).build();
}
final Response response = client.newCall(request).execute();
json = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e ){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
这是php文件:
<?php
$response = array();
require_once __DIR__ . '/db_connect2.php';
$db = new DB_CONNECT();
if (isset($_POST['name'])) {
$name = $_POST['name'];
$result = $db->query("SELECT * FROM users WHERE Name = $name");
if (!empty($result)) {
if (mysqli_num_rows($result) > 0) {
$result = mysqli_fetch_array($result);
$user = array();
$user["name"] = $result["name"];
$response["success"] = 1;
$response["users"] = array();
array_push($response["users"], $user);
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user found";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No user found";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
我收到错误:Create Response: {"success":0,"message":"No user found"}
我该如何解决?