I am using the following code to post data to my server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.kizikstudios.com/wltbo/new_score.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("name", "harry"));
nameValuePairs.add(new BasicNameValuePair("score", "12345"));
nameValuePairs.add(new BasicNameValuePair("pass", "***"));
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String feedback = EntityUtils.toString(response.getEntity());
feedback.length();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
The server is receiving the post request but it says that the size is zero bytes, and my database never gets changed. In case it is needed here is the server side script.
<?
//****Made by: Jeroen den Haan***Alias's: jeroen84 / Jer'ul****
include_once ("_data.php");
$conn = mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name,$conn);
if ($pass==$add_pass) {
if ($u_user==1) {
$sql3 = "SELECT name FROM $db_table ORDER BY name";
$result3 = mysql_query($sql3);
while($r = mysql_fetch_object($result3))
{
$tmp = "{$r->name}";
if ($name==$tmp) {
$n_exist=1;
}
}
if ($n_exist==1) {
$sql1 = "UPDATE $db_table SET score='$score' WHERE name=\"$name\"";
$result1 = mysql_query($sql1);
} else {
$sql1 = "INSERT INTO $db_table (name,score) VALUES (\"$name\",\"$score\")";
$result1 = mysql_query($sql1);
}
} else {
$sql1 = "INSERT INTO $db_table (name,score) VALUES (\"$name\",\"$score\")";
$result1 = mysql_query($sql1);
}
$sql2 = "SELECT id FROM $db_table ORDER BY score DESC";
$result2 = mysql_query($sql2);
$num = 1;
while($r = mysql_fetch_object($result2))
{
$result = mysql_db_query($db_name,"SELECT * from $db_table WHERE id='{$r->id}'");
$resultArray = mysql_fetch_array($result);
$did = $resultArray["id"];
$name = $resultArray["name"];
$score = $resultArray["score"];
if ($num>$sec_size) {
$sql3 = "DELETE FROM $db_table WHERE id='$did'";
$result3 = mysql_query($sql3);
}
$num++;
}
}
mysql_close ($conn);
?>
does anyone know why this would not work? Thank you in advance!
Where are your variables in php file that are capturing post values from other script? Can you var_dump() those variables to see if you are getting any post values to your php script?
Related
I am making an app wherein I fetch user data from the corresponding sql table using php.
<?php
$email = $_POST["email"];
#mysql_connect("localhost","root","root") or die(#mysql_error());
#mysql_select_db("dtbse") or die(#mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(#mysql_error());
$result = array();
while ($y=mysql_fetch_array($x)) {
echo $y["uname"]."<br>";
echo $y["gender"]."<br>";
echo $y["pass"]."<br>";
echo $y["address"]."<br>";
echo $y["email"]."<br>";
}
?>
Any help will be greatly apprecitated. I know this question has been a lot of times but I dont think there is something replicating this issue. Thanks.
Here is the code snippet responsible for fetching and parsing.
final ArrayList arr = new ArrayList();
arr.add(new BasicNameValuePair("email", uname));
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://xxyoxx.esy.es/getDetails.php");
httppost.setEntity(new UrlEncodedFormEntity(arr));
HttpResponse hr = httpclient.execute(httppost);
HttpEntity ent = hr.getEntity();
is = ent.getContent();
Toast.makeText(getApplicationContext(),"1 wrk ",Toast.LENGTH_LONG).show();
} catch (Exception fl) {
Toast.makeText(getApplicationContext(),"First Try error "+fl,Toast.LENGTH_LONG).show();
}
/*// Depends on your web service
httppost.setHeader("Content-type", "application/json");*/
String result=null;
try {
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(),"2 str\n "+result,Toast.LENGTH_LONG).show();
} catch (Exception sl) {
sl.printStackTrace();
Toast.makeText(getApplicationContext(),"2 err\n "+sl,Toast.LENGTH_LONG).show();
}
try{
String aa = "", b = "", c = "";
JSONArray ar = new JSONArray(result);
for (int i = 0; i < ar.length(); i++) {
JSONObject jo = ar.getJSONObject(i);
aa = jo.getString("uname");
b = jo.getString("address");
c = jo.getString("email");
}
nm.setText(aa);
addr.setText(b);
mail.setText(c);
Toast.makeText(getApplicationContext(),"3 wrk"+result,Toast.LENGTH_LONG).show();
}
catch (Exception tl){
Toast.makeText(getApplicationContext(),"3 err "+tl,Toast.LENGTH_LONG).show();
}
Strings separated by <br> are not a valid JSON array. PHP can create JSON strings using json_encode
If you need to read a JSON array in Android you need to echo a JSON array from PHP:
<?php
$email = $_POST["email"];
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("dtbse") or die(mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error());
$result = array();
$res=[];
while ($y=mysql_fetch_array($x)) {
$res[] = [
$y["uname"],
$y["gender"],
$y["pass"],
$y["address"],
$y["email"]
];
}
echo json_encode($res); //Make PHP return a valid JSON response
Also, the error suppression operators may hide valuable debug infomation which may help you diagnose other problems.
If you instead prefer to pass the JSON object to Java then you can do the following (simpler) thing.
<?php
$email = $_POST["email"];
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("dtbse") or die(mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error());
$result = array();
$res=[];
while ($y=mysql_fetch_array($x)) {
$res[] = $y;
}
echo json_encode($res); //Make PHP return a valid JSON response
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 query SQL database with IMEI variable from android device, the variable is received (verified with log.txt), however whenever I replace '00000000000000' (android virtual device IMEI) with '$androidIMEI' the results are not returned but if I explicitly use the IMEI and not the variable I receive data.
<?php
include 'config.php';
$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$androidIMEI = isset($_POST['IMEI']) ? $_POST['IMEI'] : '';
//$f = fopen("log.txt", "w");
//fwrite($f, print_r($androidIMEI, true));
//fclose($f);
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '000000000000000' ";
//$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI ' "; //not working
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['users'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
Update: (printing SQL to log file)
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI'";
$result = mysql_query($sql);
$f = fopen("log.txt", "w");
fwrite($f, print_r($sql, true));
fclose($f);
Reading Log File:
SELECT * from users WHERE Request = '0' AND IMEI = '000000000000000'
AND THIS IS WHY I HAVE NO IDEA WHY IT IS NOT WORKING
Second Update:
This might be useful, code from android, how I'm sending my IMEI to PHP:
class loadData extends AsyncTask<String, Integer, String> {
private StringBuilder sb;
private ProgressDialog pr;
private HttpResponse req;
private InputStream is;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("IMEI",IMEI));
System.out.println("IMEI: "+IMEI);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mysite/myfile.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
System.out.println("Error catch e");
}
return id;
}
Change
"SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI ' " with "SELECT * from users WHERE Request = '0' AND IMEI = '".$androidIMEI."' ".
Also you are vulnerable for SQL injections. Do not use deprecated mysql_* functions and filter your input. More information at How can I prevent SQL injection in PHP?
There is a space after $androidIMEI in your query.
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI ' ";
should be
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI';";
Try this line
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '{$android}IMEI'";
I hope it will work.
Just note those curly braces.
I am trying to make a HttpPost from my app to a php script, which will then insert data to a remote database. I'm not getting any runtime errors, but the data never gets inserted into my remote database.
Code:
public class InsertResult extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... arg0)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.<myDomain>.co.za/insertTeamResultwithCode.php");
try
{
ArrayList<NameValuePair> nameValues = new ArrayList<NameValuePair>(10);
nameValues.add(new BasicNameValuePair("Code", password));
nameValues.add(new BasicNameValuePair("Section", section));
nameValues.add(new BasicNameValuePair("Gender", gender));
nameValues.add(new BasicNameValuePair("WinningTeam", newResult.getWinningTeam()));
nameValues.add(new BasicNameValuePair("LosingTeam", newResult.getLosingTeam()));
nameValues.add(new BasicNameValuePair("FixtureD", newResult.getDate()));
nameValues.add(new BasicNameValuePair("FixtureT", newResult.getTime()));
nameValues.add(new BasicNameValuePair("Venue", newResult.getVenue()));
nameValues.add(new BasicNameValuePair("Court", newResult.getCourt()));
nameValues.add(new BasicNameValuePair("Texts", newResult.getText()));
httppost.setEntity(new UrlEncodedFormEntity(nameValues));
HttpResponse response = httpclient.execute(httppost);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
GoToJarvisDashboard();
}
}
And PhP script:
<?php
//Code verifications
$Code = $_GET['Code'];
//Variables for SQL INSERT
$Section = $_GET['Section'];
$Gender = $_GET['Gender'];
$WinningTeam = $_GET['WinningTeam'];
$LosingTeam = $_GET['LosingTeam'];
$FixtureD = $_GET['FixtureD'];
$FixtureT = $_GET['FixtureT'];
$Venue = $_GET['Venue'];
$Court = $_GET['Court'];
$Texts = $_GET['Texts'];
$SetsWon = $_GET['SetsWon'];
$SetsLost = $_GET['SetsLost'];
$Winner_Score = $_GET['Winner_Score'];
$Loser_Score = $_GET['Loser_Score'];
$dbname = '<dbName>';
$dbuser = '<user>';
$dbpass = '<password>';
$dbhost = '<host>t';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die ("Unable to Connect to '$dbhost'");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SQL = "SELECT * FROM squasdlw_db1.validationCodes WHERE Code = '$Code'";
$codeValid = mysqli_query($connect, $SQL) or die (mysqli_error($connect));
$response["no"] = array();
if (mysqli_num_rows($codeValid) > 0)
{
echo "Code is valid\n\n";
//Insert Result
$query = "INSERT INTO squasdlw_db1.jarvisTeamResults (Section,Gender,WinningTeam,LosingTeam,FixtureD,FixtureT,Venue,Court,Texts,SetsWon,SetsLost,Winner_Score,Loser_Score) VALUES('$Section','$Gender','$WinningTeam','$LosingTeam','$FixtureD','$FixtureT','$Venue','$Court','$Texts','$SetsWon','$SetsLost','$Winner_Score','$Loser_Score')";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Result successfully submitted to Jarvis Remote Database: Table -> jarvisTeamResults\n\n" ;
//Update Winner on jarvisLogs
$query = "UPDATE squasdlw_db1.jarvisLogs SET Points = Points + '$Winner_Score', Played = Played + 1, Won = Won + 1 WHERE Gender = '$Gender' AND Section = '$Section' AND Team = '$WinningTeam'";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Log update for '$WinningTeam': Table -> jarvisLogs\n\n";
//Update Winner on jarvisLogs
$query = "UPDATE squasdlw_db1.jarvisLogs SET Points = Points + '$Loser_Score', Played = Played + 1, Lost = Lost + 1 WHERE Gender = '$Gender' AND Section = '$Section' AND Team = '$LosingTeam'";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Log update for '$LosingTeam': Table -> jarvisLogs\n\n";
$response["isValid"] = true;
echo json_encode($response);
}
else
{
$response["isValid"] = false;
echo "The code is not valid\n";
echo json_encode($response);
}
mysqli_close($connect);
?>
Whats even weirder is that if I try this in a web browser, it works fine and the data does get added to the remote database-
http://www.<myDomain>.co.za/insertTeamResultwithCode.php?Code=<password>&Section=A&Gender=Men&WinningTeam=NW&LosingTeam=KZN&FixtureD=2015-05-25&FixtureT=09:00:00&Venue=Puk&Court=6&Texts=Andrew%20(NW)%20beat%20Kevin%20(WP)%203-1&SetsWon=15&SetsLost=5&Winner_Score=15&Loser_Score=5
Please help out, I have no idea what is going wrong because it does not create runtime errors? I am about to go crazy...
You are doing an HttpPost so you should get your data via POST and not GET
//Code verifications
$Code = $_POST['Code'];
//Variables for SQL INSERT
$Section = $_POST['Section'];
$Gender = $_POST['Gender'];
$WinningTeam = $_POST['WinningTeam'];
$LosingTeam = $_POST['LosingTeam'];
$FixtureD = $_POST['FixtureD'];
$FixtureT = $_POST['FixtureT'];
$Venue = $_POST['Venue'];
$Court = $_POST['Court'];
$Texts = $_POST['Texts'];
$SetsWon = $_POST['SetsWon'];
$SetsLost = $_POST['SetsLost'];
$Winner_Score = $_POST['Winner_Score'];
$Loser_Score = $_POST['Loser_Score'];
Or change your android code to make GET requests :
HttpGet httpget = new HttpGet("http://www.example.com/insertTeamResultwithCode.php");
You are sending POST in android BUT you are expecting GET in php which are not the same.
Change the $_GET to $_POST and it will work.
Here a post that will tell you difference between then
Here another with some more details
This is my java code
public void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.0.104/rocket/assign_job.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(1);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
//int smsNum = Integer.parseInt(smsCode.getText().toString());
nameValuePairs.add(new BasicNameValuePair("smsCode", smsCode));// $Edittext_value = $_POST['Edittext_value'];
//nameValuePairs.add(new BasicNameValuePair("userName", rocketName));
Log.d("smsCode ===", smsCode);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
//response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
runOnUiThread(new Runnable() {
public void run() {
Log.d("PHP Response: ", response);
pDialog.dismiss();
}
});
if (response.equalsIgnoreCase("success")) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UserPage.this, "Job Assigned", Toast.LENGTH_SHORT).show();
}
});
} else {
showAlert();//testing bitbuckettt
}
} catch (Exception e) {
pDialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
This is my PHP Code:
<?php
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if(isset($_POST['smsCode'])){
$smsCode = $_POST['smsCode'];
$query_search = "SELECT * FROM confirmedrequest WHERE smsCode='".$smsCode."'";
$query_exec = mysqli_query($db->getConnection(),$query_search) or die(mysqli_error($db->getConnection()));
$row = mysqli_num_rows($query_exec);
if($row == 0){
echo "failed";
}else{
echo "success";
$rocketName = mysqli_real_escape_string($db->getConnection(),$_POST["userName"]);
$sql_update = "UPDATE confirmedrequest SET jobTakenBy = '$rocketName' WHERE smsCode = $smsCode ";
$sql_exec = mysqli_query($db->getConnection(),$sql_update) or die(mysqli_error($db->getConnection()));
}
}else{
echo "Empty code";
}
?>
The PHP Response in logcat is always failed even though the code matches. I have tried to debug it for several hours but still cant solve. All I want is to run the code below (response.equalsIgnoreCase("success")) when the code matches.
You have to set the headers in order to the response to be formatted in a correct way:
$db = new DB_CONNECT();
if(isset($_POST['smsCode'])){
$smsCode = $_POST['smsCode'];
$query_search = "SELECT * FROM confirmedrequest WHERE smsCode='".$smsCode."'";
$query_exec = mysqli_query($db->getConnection(),$query_search) or die(mysqli_error($db->getConnection()));
$row = mysqli_num_rows($query_exec);
if($row == 0){
http_response_code(500);
echo "failed";
}else{
http_response_code(200);
echo "success";
$rocketName = mysqli_real_escape_string($db->getConnection(),$_POST["userName"]);
$sql_update = "UPDATE confirmedrequest SET jobTakenBy = '$rocketName' WHERE smsCode = $smsCode ";
$sql_exec = mysqli_query($db->getConnection(),$sql_update) or die(mysqli_error($db->getConnection()));
}
}else{
http_response_code(400);
echo "Empty code";
}