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
Related
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.
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";
}
I am trying to insert multiple (1-50) entries from an Android application to an external Mysql database. I perfectly got a PHP script to work for single INSERT queries. But I am failing so far to make this work for a whole array of entries, most likely due to my limited understanding of PHP.
Android code:
List<NameValuePair> upload_array = new ArrayList<NameValuePair>();
upload_array.add(new BasicNameValuePair("mFirstname[0]", "FirstName 1"));
upload_array.add(new BasicNameValuePair("mFirstname[1]", "FirstName 2"));
upload_array.add(new BasicNameValuePair("mLastname[0]", "LastName 1"));
upload_array.add(new BasicNameValuePair("mLastname[1]", "LastName 2"));
upload_array.add(new BasicNameValuePair("mNickname[0]", "NickName 1"));
upload_array.add(new BasicNameValuePair("mNickname[1]", "NickName 2"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://url/script.php");
HttpResponse response = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(upload_array));
response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
}
And in PHP:
<?php
$connect = mysqli_connect("***","***","***", "***");
if(mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "success";
}
$query = mysqli_prepare("INSERT INTO `namelist` (`firstname`,`lastname`,`nickname`)
VALUES(?,?,?)");
$mFirstname = $_POST['mFirstname'];
$mLastname = $_POST['mLastname'];
$mNickname = $_POST['mNickname'];
foreach($mFirstname as $key as $key => $value) {
$query->bind_param('sss',$value["mFirstname"],$value["mLastname"],$value["mNickname"];
$query->execute();
}
mysqli_close($connect);
?>
Is the mistake happening in the Android part of the code already or does this PHP script just not read the data I sent properly? Any insight would be very welcome.
Ok, I made this work using a JSON Array. In case anyone has use for it, here's how it goes:
Android, create JSON String:
//Create JSON string start
String json_string ="{\"upload_fishes\":[";
//Repeat and loop this until all objects are added (and add try+catch)
JSONObject obj_new = new JSONObject();
obj_new.put("fish_id", your_looped_string_1[i]);
obj_new.put("fish_lat", your_looped_string_2[i]);
obj_new.put("fish_lon", your_looped_string_3[i]);
json_string = json_string + obj_new.toString() + ",";
//Close JSON string
json_string = json_string.substring(0, json_string.length()-1);
json_string += "]}";
Android send data to PHP (add try+catch):
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
String url = "http://yourserver.com/script.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json_string.getBytes("UTF8")));
request.setHeader("json", json_string);
HttpResponse response = client.execute(request);
Log.d("FISHY", response.getStatusLine().toString());
PHP script:
<?php
//CONNECT TO THE DATABASE
$DB_HOST = 'yourhost.com';
$DB_USER = 'user';
$DB_PASS = 'password';
$DB_NAME = "db_name";
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if(mysqli_connect_errno())
{
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// echo "Connected to MySQL";
}
$postdata = file_get_contents("php://input");
$data = json_decode($postdata, true);
if (is_array($data['upload_fishes'])) {
foreach ($data['upload_fishes'] as $record) {
$fid = $record['fish_id'];
$flat = $record['fish_lat'];
$flon = $record['fish_lon'];
mysqli_query($mysqli,"INSERT INTO `fishes`(`fish_type_id`, `fish_lat`, `fish_lon`) VALUES ($fid, $flat, $flon)");
}
}
mysqli_close($mysqli);
?>
Hi i am using php to connect my android app to mysql but the get method is not passing the value to the php file.
This is my code.
private void executeAjaxRequest(){
String url = mDataUrl+"?request="+mRequest+"&outlet_id="+mOutletID;
Log.v("url",url);
System.out.println("This is StoreActivity " +url);
AsyncHttpClient httpclient = new AsyncHttpClient();
httpclient.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
setOutletData(response);
Log.i("TAG",response);
}
});
}
It should pass the outletid and mrequest to the php file to get the data from the database.
Can you tell me where i am going wrong.
error_reporting(0);
//$url = $_GET['url'];
$mR = $_GET["mRequest"];
$mOid = $_GET["mOutletID"];
//$mloc = $_GET['mLocation'];
//connect to the db
//echo $mOid;
$user = "root";
$pswd = "";
$db = "recommendations_db";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//if($mR == 'outlets' && $mloc = 'all'){
$query = "SELECT outlet_id,outlet_name,outlet_location,outlet_image FROM outlets WHERE outlet_id = '$mOid'";
$result = mysql_query($query) or die("Unable to execute query because : " . mysql_error());
//echo $result ." ". $mOid;
while($row = mysql_fetch_assoc($result))
{
$query2 = "SELECT a.item_id,a.item_name,a.item_image FROM items a,outlets b,recommendations c WHERE a.item_id = c.item_id AND b.outlet_id = c.outlet_id AND b.outlet_id = ".$row['outlet_id'];
$row['recommended_products']=array();
$result2 = mysql_query($query2) or die("Unable to execute query because : " . mysql_error());
//echo $row;
while($row2 = mysql_fetch_assoc($result2)){
$row['recommended_products'][]=$row2;
//echo $row;
}
$output[] = $row;
}
print( json_encode($output) );
mysql_close($conn);
Are you able to retrieve the request and outletid on your server ? If the request is indeed and SQL request it should be url encoded to avoid truncating the URL with some potentially "dangerous" characters.
You should override the method onFailure from AsyncHttpResponseHandler to handle any possible error. What you could also try is to use the RequestParams instead of putting the parameters and their values in the URL. You can use them like so:
RequestParams params = new RequestParams();
params.put("request", "mRequest");
params.put("outlet_id", "mOutletID");
AsyncHttpClient client = new AsyncHttpClient();
client.get("URL", params, new AsyncHttpResponseHandler() {
#Override
public void onFailure(Throwable arg0, String arg1) {
// Handle the error
}
#Override
public void onSuccess(String arg0) {
// Do stuff with the result
}
});
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?