I'm comparing the username and password from the user input to the database data, and I used count to check if it is equal to 1 or 0.
If it's equal to 1, the editText should be set to 1, and if it's 0 it should be set to 0.
My problem is, it's always set to 0 even if the username and password is correct.
here is the name value pair and connection to the database:
username = etlogUsername.getText().toString();
password = etlogPassword.getText().toString();
String output = "";
//setting the NameValuePair
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
//adding the string variables inside the nameValuePairs
nameValuePairs.add(new BasicNameValuePair("user_username", username));
nameValuePairs.add(new BasicNameValuePair("user_password", password));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://thesis-account.byethost7.com/workout_select_username.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//getting the response
HttpResponse response = httpclient.execute(httppost);
//setting up the entity
HttpEntity entity = response.getEntity();
is = entity.getContent();
here is the json that will read the data:
JSONArray jArray= new JSONArray(output);
for(int i = 0; i <jArray.length() ; i++){
JSONObject json = jArray.getJSONObject(i);
COUNT_user_id = json.getInt("num_rows");
if(COUNT_user_id == 1)
{
isEqual = true;
}
}
etlogUsername.setText(COUNT_user_id+"");
and here is the php file:
$sql = mysql_query("SELECT COUNT(user_id) AS num_rows FROM tbl_users
WHERE user_username='{ $username}' && user_password = '{$password}' ");
while($row=mysql_fetch_assoc($sql))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
Related
{"college1":{"data":[{"id":"1","name":"nithin","location":"kannur s","time":"2016-06-20 12:06:30"},{"id":"2","name":"riy","location":"sdsdvxc","time":"2016-06-20 12:49:52"},{"id":"3","name":"royop","location":"kjpooj","time":"2016-06-20 06:15:36"},{"id":"4","name":"butr","location":"kjpooj","time":"2016-06-20 06:16:52"},17:17:03"}],"last_date":["2016-06-20 18:18:15"]}}
json data
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lasttime",lasttime));
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(ip);
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String result="";
if(is !=null)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
is.close();
i am trying to develop communication with android and wamp .when trying to send sqlite date to mysql database. it shows this error message. this is my web service.
$latest = '';
$datetime=mysql_query("SELECT MAX(time) AS latest from college1");
while ($row = mysql_fetch_assoc($datetime))
{
$latest = $row['latest'];
}
if(isset($_POST['lasttime']))
{
$dates=$_POST['lasttime'];
$datetime=mysql_query("SELECT * from college1 WHERE time > '{$dates}'");
while ($row = mysql_fetch_assoc($datetime))
{
//print_r($row);
//$array1[] = $row;
$retArr['college1']['data'][] = $row;
$retArr[$row['id']] = $row;
$retArr[$row['id']]['latest'] = $latest;
}
$retArr = json_encode($retArr);
echo $retArr;
//echo($retArr);
}
mysql_close($con);
?>
org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject.
this error shows when passing data to server and respose as null
I am trying to send a string to php script using namevaluepair. But i couldn't receive it on the other side. Here is my code.
protected String doInBackground(String... args) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Username",code ));
Log.v("username", code);
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.42.21:8080/sellapp/menuitem.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish {}
}
return result;
}
Here i want to pass the value in the string code to my php script. my php script is
$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id=$_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "
select
cust_code, segment_type, cust_name, cust_address, cust_payment_type, cust_credit_limit, cust_cr_balance
from customer where cust_code='".$cst_id."'
";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push(
$result,
[
'cust_id'=>$row[0],
'cust_seg'=>$row[1],
'cust_name'=>$row[2],
'cust_type'=>$row[3],
'cust_ad'=>$row[4],
'cust_cr'=>$row[5],
'cust_bl'=>$row[6]
]
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
When I am giving the value directly to the php it works. But through name/value pair it returns a null array as result.
Please help me to get an answer.I tried questions related to it. But didn't worked.
<?php
$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id = $_POST['Username']; // --------- not $_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "select cust_code,segment_type,cust_name,cust_address,cust_payment_type,cust_credit_limit,cust_cr_balance from customer where cust_code='".$cst_id."' ";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
['cust_id'=>$row[0],
'cust_seg'=>$row[1],
'cust_name'=>$row[2],
'cust_type'=>$row[3],
'cust_ad'=>$row[4],
'cust_cr'=>$row[5],
'cust_bl'=>$row[6]
]);
}
//echo json_encode(array("result"=>$result));
echo json_encode($result);
mysqli_close($con);
?>
I am trying to get All the list of names and surnames from a mysql database but only for a certain username and password by which an user is accessing the service.
I tried with the code below but it seems that is not working. Actually the JSONArray i get back is EMPTY.
Here my java code and Php code (which is on the server).
The whole code is working great if I don't filter by username and password so actually i receive back the list. But as I try to filter by username and password the JsonArray is Null.
Please I will appreciate any clue!
public class ApiConnector {
public JSONArray GetAllCustomers(User user){
String url = "http://giacomoci.co.uk/FetchallDataList.php";
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
DefaultHttpClient httpClient = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(url);
JSONArray jsonArray = null;
try {
//DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpGet httpGet = new HttpGet(url);
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = httpClient.execute(post);
HttpEntity httpEntity = httpResponse.getEntity();
if(httpEntity != null){
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
}catch (JSONException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return jsonArray;
}
}
And here my PHP code
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT name, surname FROM Contacts WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
$user[] = array();
while($row = mysqli_fetch_assoc($statement)){
$user[] = $row;
}
echo json_encode($user);
mysqli_close($con);
So if I delete "Where username = ? AND password = ?" and the following line everything goes fine, but I get names and surnames for all the usernames and passwords, as I don't want. What's wrong with this code?
$username = $_POST["username"];
$password = $_POST["password"];
Replace those _POST with _GET
$username = $_GET["username"];
$password = $_GET["password"];
Currently i am trying to send an ArrayList data to php server but cannot make it. the ArrayList include data which are: foodname, foodprice, quantity, remark and they all store inside an object order. it is something like this
Order order = new Order();
order.setFood_name(fooddetail.getString(TAG_FOODNAME));
order.setFood_price(fooddetail.getString(TAG_FOODPRICE));
order.setNumber(Integer.toString(number));
order.setRemark(remark.getText().toString().trim());
Global.orderList.add(order);
and now i want to pass them into php server, this is the code i tried
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/android_user/print.php");
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("count", Integer.toString(count)));
for(int i=0;i<Global.orderList.size();i++)
{
nameValuePairs.add(new BasicNameValuePair("username", Global.UserID));
nameValuePairs.add(new BasicNameValuePair("food_name", Global.orderList.get(i).getFood_name()));
nameValuePairs.add(new BasicNameValuePair("food_price", Global.orderList.get(i).getFood_price()));
nameValuePairs.add(new BasicNameValuePair("quantity", Global.orderList.get(i).getQuantity()));
nameValuePairs.add(new BasicNameValuePair("remark", Global.orderList.get(i).getRemark()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String res = httpclient.execute(httppost, responseHandler);
if(res.equalsIgnoreCase("Order successfully sent"))
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(OrderListActivity.this,"Order Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(OrderListActivity.this, LoginActivity.class));
}
else if(res.equalsIgnoreCase("Oops! Order failed to submit"))
{
alertmessage = "Oops! Order failed to submit!";
showAlert();
}
else
{
alertmessage = res.toString();
showAlert();
}
}
catch(Exception e)
{
e.printStackTrace();
}
and this is the php side code
for($i=0; $i<count($_POST['food_name']);$i++)
{
$food_name = $_POST['food_name'][$i];
$food_price = $_POST['food_price'][$i];
$quantity = $_POST['quantity'][$i];
$remark = $_POST['remark'][$i];
$username = $_POST['username'][$i];
$result = mysql_query("INSERT INTO orderlist(food_name, food_price, quantity, remark, username) VALUES('$food_name', '$food_price', '$quantity','$remark','$username')");
}
My question is, how to send multiple rows of data and store them in to database? currently i am able to store only one row or the last row of data..
try this:
$food_name = $_POST['food_name'];
$food_price = $_POST['food_price'];
$quantity = $_POST['quantity'];
$remark = $_POST['remark'];
$username = $_POST['username'];
for($i=0; $i<count($_POST['food_name']);$i++)
{
$result = mysql_query("INSERT INTO orderlist(food_name, food_price, quantity, remark, username) VALUES('$food_name[$i]', '$food_price[$i]', '$quantity[$i]','$remark[$i]','$username[$i]')");
}
This problem: after UrlEncodedFormEntity(nameValuePairs) your objects state same name, it is set last data:
nameValuePairs.add(new BasicNameValuePair("username", Global.UserID));
nameValuePairs.add(new BasicNameValuePair("food_name", Global.orderList.get(i).getFood_name()));
nameValuePairs.add(new BasicNameValuePair("food_price", Global.orderList.get(i).getFood_price()));
nameValuePairs.add(new BasicNameValuePair("quantity", Global.orderList.get(i).getQuantity()));
nameValuePairs.add(new BasicNameValuePair("remark", Global.orderList.get(i).getRemark()));
Solution this problem you need add prefix to pair name (Example: "username" + loopIndexNumber) or send data send your data separately for each.
private void AddGroupTasks(){
title1 = tTitle.getText().toString();
detail1 = tDetail.getText().toString();
ArrayList<NameValuePair> b = new ArrayList<NameValuePair>();
Tasks = new ArrayList<String>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost ("http://203.209.111.88/AddGroupTasks.php");
httppost.setEntity(new UrlEncodedFormEntity(b));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line=null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
So, When I click add,the information is supposed to be added to database. However, it gives a null value. By the way, I'm writing a to-do list app.
$Title = $_REQUEST['tTitle'];
$Detail = $_REQUEST['tDetail'];
$Group = $_REQUEST['spin'];
$DueDate = $_REQUEST['tDueDate'];
$Title = "'".$Title."'";
$Detail = "'".$Detail."'";
$Group = "'".$Group."'";
$DueDate = "'".$DueDate."'";
print $Title;
$database = "CloudList";
mysql_connect("localhost","root","1234");
mysql_select_db($database) or die("Unable to select database");
$q = "INSERT INTO message(group_name,message_title,message_details,message_due) VALUES($Group,$Title,$Detail,$DueDate)";
$result = mysql_query($q);
print $q;
mysql_close();
Here, This is my PHP Script.
Try this code, replace with your code and let me know what happen,
private void AddGroupTasks(){
title1 = tTitle.getText().toString();
detail1 = tDetail.getText().toString();
ArrayList<NameValuePair> b = new ArrayList<NameValuePair>();
Tasks = new ArrayList<String>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost ("http://203.209.111.88/AddGroupTasks.php");
b.add(new BasicNameValuePair("tTitle",
"anyTitle"));
b.add(new BasicNameValuePair("tDetail",
"anyDetail"));
b.add(new BasicNameValuePair("spin",
"AnythingaboutSpin"));
b.add(new BasicNameValuePair("tDueDate",
"anytDueDate"));
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(b, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line=null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Try to set quotes in your Values section. It should look like:
$q = "INSERT INTO message(group_name,message_title,message_details,message_due) VALUES('$Group','$Title','$Detail','$DueDate')";