I have PHP code which connects to MySql and encodes data to JSON. Later I would filter it and get specific JSON object. It worked fine while I was using one NameValuePair object but now I want to use variables like username and password. Now I am getting this alert in logcat Error parsing data .org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray.
How should I change the code that could work properly ?
$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));
Code which sends request:
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());
}
Edited
$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));
If this is the entire code that you have put on your server side then i guess you need to first take values into $username
and $password
using the $_POST[]
method like this
$username=$_POST["usern"];
$password=$_POST["passw"];
and the same for password
.
since as of now there is no value in the variables your SELECT
statement returns null
value which is sent to client in JSON
format which gives a null
value error.
Based on your comment "I used LIKE while I was trying only username and it worked fine."
In what form are you storing your password? Plain text (I hope not) or hashed? If hashed, where do you perform hashing? In php you don't if it's whole code, do you do it in your java code? If not, that's your answer.
As for the LIKE - it did work, of course. LIKE is less strict than = and it generates a significant overhead. It should only be used in very simple search statements (VERY SIMPLE), certainly not in authorization.