1

我有连接到 MySql 并将数据编码为 JSON 的 PHP 代码。稍后我会过滤它并获取特定的 JSON 对象。当我使用一个 NameValuePair 对象时它工作得很好,但现在我想使用用户名和密码等变量。现在我在 logcat 中收到此警报 解析数据时出错 .org.json.JSONException:org.json.JSONObject$1 类型的值 null 无法转换为 JSONArray。

我应该如何更改可以正常工作的代码?

$q=mysql_query("SELECT username, firstname, lastname, email, phone1, skype, city, description FROM mdl_user WHERE username LIKE '$username' AND password LIKE '$password'");
while($e=mysql_fetch_assoc($q))
    $output[]=$e;
print(json_encode($output));

发送请求的代码:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("usern",""+usr));
        nameValuePairs.add(new BasicNameValuePair("passw",""+psw));
        InputStream is = null; 
        String result = "";
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://ik.su.lt/~jbarzelis/Bdarbas/getUserInfo.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());
        }

已编辑

$username = mysql_real_escape_string($_REQUEST['usern']);
$password = mysql_real_escape_string($_REQUEST['passw']);
$q=mysql_query("SELECT username, firstname, lastname, email, phone1, skype, city, description
FROM mdl_user WHERE username LIKE '$username' AND password LIKE '$password'");
while($e=mysql_fetch_assoc($q))
    $output[]=$e;
print(json_encode($output));
4

2 回答 2

1

如果这是您放在服务器端的整个代码,那么我想您需要首先将值输入$username$password使用这样的$_POST[]方法

$username=$_POST["usern"];
$password=$_POST["passw"];

和同样的password

因为到目前为止,您的SELECT语句返回的变量中没有值,该值以给出值错误null的格式发送给客户端。JSONnull

于 2012-04-10T20:16:58.487 回答
1

根据您的评论“我在尝试只使用用户名时使用了 LIKE,它运行良好。”

您以什么形式存储您的密码?纯文本(我希望不是)还是散列?如果散列,你在哪里执行散列?在php中,如果它是整个代码,你不会在你的java代码中这样做吗?如果没有,这就是你的答案。

至于 LIKE - 当然,它确实有效。LIKE 没有 = 严格,它会产生很大的开销。它应该只用于非常简单的搜索语句(VERY SIMPLE),当然不能用于授权。

于 2012-04-10T20:44:26.770 回答