I have a signup form in a android app which consist of a username and a password. I want that when a user click the submit button of the signup form then the username and password will be saved into a web-database(mySql database).
When a user press submit button then sendPostRequest(givenUsername, givenPassword); is executed.
and sendPostRequest() function is like that
private void sendPostRequest(String givenUsername, String givenPassword) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/imon.php");
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("working")){
Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
And my imon.php is like that:
<?php
$varUsername = $_POST['paramUsername'];
$varPassword = $_POST['paramPassword'];
if($varUsername != "" && $varPassword != ""){
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('post_db', $con);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$sql="INSERT INTO post_table (username,password)
VALUES
('$varUsername ','$varPassword')";
if (!mysql_query($con,$sql))
{
die('Error: ' . mysql_error($con));
}
echo 'working';
}else
{
echo 'invalid';
}
?>
But data is not inserted into my-sql database.
What am i wrong here??
What should i do to insert the data of signup form into web database??
You can't do this
mysql_connect('localhost', 'root', '');
and then do this
if (!mysqli_query($con,$sql))
mysql and mysqli are separate extensions. you can't share resources from one with another.
mysqli_query() and mysql_query() doesn't take the same param order. the first param of mysql_query() is the query. where in mysqli_query first parameter is the connection resource. You were also intermixing the connections earlier as well.
Related
Data is not inserting in MySql from android there is no error in the code, i have defined them using AsyncThread - doInBackground and onPostExecute..Its showing the toast what i have defined in Json Object Try Catch Method 'Sorry Try Again' in else condition if data is not inserted.
InputStream is = null;
String res = null;
String line = null;
int code;
onClick Code
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
question = addque.getText().toString();
choice1 = addc1.getText().toString();
choice2 = addc2.getText().toString();
choice3 = addc3.getText().toString();
answer = addanswer.getText().toString();
Explanation = addexplan.getText().toString();
AsyncTaskRunner Class
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("question", question));
nameValuePairs.add(new BasicNameValuePair("choice1", choice1));
nameValuePairs.add(new BasicNameValuePair("choice2", choice2));
nameValuePairs.add(new BasicNameValuePair("choice3", choice3));
nameValuePairs.add(new BasicNameValuePair("answer", answer));
nameValuePairs.add(new BasicNameValuePair("Explanation",
Explanation));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://192.168.43.4/insert/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
res = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
JSONObject json_data;
json_data = new JSONObject(res);
code = json_data.getInt("code");
if(code==1)
{
Toast.makeText(getActivity(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
}
PHP Code
<?php
$host='localhost';
$uname='root';
$pwd='';
$db="quizDB";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$question=$_REQUEST['question'];
$choice1=$_REQUEST['choice1'];
$choice2=$_REQUEST['choice2'];
$choice3=$_REQUEST['choice3'];
$answer=$_REQUEST['answer'];
$Explanation=$_REQUEST['Explanation'];
$flag['code']=0;
if($r=mysql_query("insert into quizquestion values('$question','$choice1',
$choice2, '$choice3', '$answer', '$Explanation') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
Correct me if i am wrong.
first get all string you want to insert and then call AsyncTask. may be this solve .
question = addque.getText().toString();
choice1 = addc1.getText().toString();
choice2 = addc2.getText().toString();
choice3 = addc3.getText().toString();
answer = addanswer.getText().toString();
Explanation = addexplan.getText().toString();
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
and also change this 2 line . pass UTF-8 to UrlEncodeFormEntity
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
httppost.setEntity(formEntity);
Edited
I think you forget to add concatination onto $choice2 , and change query like this. pass first fieldName and then Values.
$sql = "INSERT INTO MyGuests (fieldName1, fieldName2, fieldName3,fieldName4,fieldName5,fieldName6)
VALUES ('$question','$choice1','$choice2', '$choice3', '$answer', '$Explanation')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
$flag['code']=1;
echo"hi";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
i want to send all contacts with contact name and number in one row in one array in my android application like
john => "+92312xxxxxxx" ,
Right now i'm using namevaluepairs to post two arrays but it's not working like :
public class ContactList extends Activity {
public TextView outputText;
String phoneNumber = null;
String names = null;
String[] keyValue;
String[] kes;
int Count;
String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
//Http connection
InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
for (int i = 0; i < Count ; i++)
{
nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(ClientProtocolException e)
{
Log.e("ClientProtocol","Log_tag");
e.printStackTrace();
System.out.println("Excep: "+e);
}
catch(IOException e)
{
Log.e("Log_tag","IOException");
e.printStackTrace();
}
String result = "";
try
{
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");
}
reader.close();
is.close();
result=sb.toString();
Log.i("Response", "result "+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
s= s +";"+ jArray.getString(i) + "\n";
}
}
catch (Exception e)
{
Log.e("Response", "error fetching indexes" + e);
}
String[] friends= s.split(";");
StringBuffer output = new StringBuffer();
for (int i = 0; i < friends.length; i++)
{
Log.i("List","Your friends namee"+friends[i]);
output.append("\n Your friend's number"+ friends[i]);
}
}
//Fetch Contacts
public void fetchContacts() {
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
//String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
// String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
Count = cursor.getCount();
if (cursor.getCount() > 0) {
keyValue= new String[Count];
kes= new String[Count];
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext())
{
int i=0;
String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber +=":"+ stu;
names +=":" + name;
Log.i("List",stu + name +"\n" );
}
phoneCursor.close();
}
}
}
keyValue = phoneNumber.split(":");
kes = names.split(":");
Log.i("List","24th"+keyValue[23]);
Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
}
PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names
i'm stuck with sending and receving part
Here is php code
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'verification');
define('DB_USER','root');
define('DB_PASSWORD','');
// 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){
//or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{ echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];
$j++;
}
else
{
;
}}
}
echo (json_encode($friends));
?>
You'll get a URL now that would look like:
www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.
I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.
Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.
my codes is fine, not returning any errors but the values being retrieved are the same as the previous field..for example, if i set table3 to 'HELLO' then table4 is also 'HELLO' which is kinda wrong,i wanted separate values..here is my code...
my SigninActivity:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField, sampleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView roleField,TextView sampleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
this.sampleField = sampleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://XXX.XXX.X.X/XXX/ins.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://XXX.XXX.X.X/XXX/sel.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
}
my select.php file (sel.php):
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
This is where your problem is:
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
If you want different values for sampleField and roleField, you should set different values.
Update
I see where your other problem is. In the un-updated PHP source, you are selecting both role and sample from the database table, but you are outputting only role because $data equals $row[0]. If you want sample as well, you would need to retrieve $row[1] as well.
Or you could also use $row["role"] and $row["sample"] to get the values returned from the database table.
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
if($row){
// returns a json object in the form
// {"role":"<role-from-database>","sample":"<sample-from-database>"}
$output = array("role" => $row["role"] ,"sample" => $row["sample"]);
echo json_encode($output);
}
mysqli_close($con);
?>
With the updated PHP source, you should process the JSON object in your SigninActivity.
Update 2
#Override
protected void onPostExecute(String result){
String role = "", sample = "";
// read the json object with JsonReader
JsonReader reader = new JsonReader(new StringReader(result));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("role")) {
role = reader.nextString();
} else if (name.equals("sample")) {
sample = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
// set the text here
}
Let me know if this helps.
The code queries the user table ("name") to retrieve the Chinese name corresponding to the username (unique) input by user.
In DEBUG mode, found that username in $_POST['username'] is blank when passed to PHP. I can retrieve the Chinese name in DEBUG mode. Please help to figure out what's wrong in parameter-passing.
Android part to send a POST request to PHP.
public class SigninActivity extends AsyncTask<String,Void,String> {
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://www.example.com/login.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://www.example.com/login.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
// Code in PHP
$con = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con, $mysql_database) or die("Could not select database");
if (DEBUG) {
echo "Connected to database $mysql_database";
}
mysqli_set_charset($con, 'utf8');
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
if (DEBUG) {
$username = "b";
}
$qry1 = "SELECT c_f_name FROM name where username = \"$username\" ";
$result = mysqli_query($con, $qry1);
if(DEBUG) {
echo "This is the username: ";
echo $username;
if ($result) {
echo $username;
//successful query
if (mysqli_num_rows($result) > 0) {
echo "query successful -
";
echo mysqli_num_rows($result);
} else {
echo "query successful-0 rows
";
}
} else {
// query not successful
echo "Query unsuccessful";
}
}
$row = mysqli_fetch_array($result);
//Since there is only 1 record that match, just retrieve the first and only record
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
You are passing your username/password through the url
http://www.example.com/login.php?username="+username+"&password="+password
Therefor request your values using either $_GET['username'] or $_REQUEST['username'].
you are passing GET variable and trying to retrieve variables from POST method.. that won't work you also have to use $GET['variable_name'] or $REQUEST['variable_name'] to retrieve data from that url.
its a simple rule that if you are passing your data through get or post method than also you have to retrieve that data as same method.
I'm trying to update a row in my database via my android app. My pulling from the database is working but I'm having trouble with the updating. My code for updating is as follows:
My AsyncTask class:
private class UpdateAnimalTask extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... arg0)
{
try
{
ID = (EditText) findViewById(R.id.eTid);
Name = (EditText) findViewById(R.id.eTname);
Type = (EditText) findViewById(R.id.eTtype);
Breed = (EditText) findViewById(R.id.eTbreed);
Gender = (EditText) findViewById(R.id.eTgender);
Injuries = (EditText) findViewById(R.id.eTinjuries);
Treat = (EditText) findViewById(R.id.eTtreat);
String nM = Name.getText().toString();
String tP = Type.getText().toString();
String bR = Breed.getText().toString();
String gE = Gender.getText().toString();
String iN = Injuries.getText().toString();
String tR = Treat.getText().toString();
ArrayList<NameValuePair> up = new ArrayList<NameValuePair>();
up.add(new BasicNameValuePair("name", nM));
up.add(new BasicNameValuePair("type", tP));
up.add(new BasicNameValuePair("breed", bR));
up.add(new BasicNameValuePair("gender", gE));
up.add(new BasicNameValuePair("injuries", iN));
up.add(new BasicNameValuePair("treatment", tR));
String phpLink = "http://select.garethprice.co.za/update.php?name=" + nM;
Log.e("Test", up.toString());
dbUpdate(up, phpLink);
Log.e("Test", up.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in uploading " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
if(result)
{
Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
}
}
}
My dbUpdate method which is being called inside my asynctask class:
public void dbUpdate(ArrayList<NameValuePair> data, String phpL)
{
InputStream iS = null;
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(phpL);
httppost.setEntity(new UrlEncodedFormEntity(data));
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());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
}
}
My php:
<?php
include_once 'db.php';
$con=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)or die("cannot connect");
mysql_select_db(DB_DATABASE)or die("cannot select DB");
$nM = $_GET['name'];
$tP = $_POST['type'];
$bR = $_POST['breed'];
$gE = $_POST['gender'];
$iN = $_POST['injuries'];
$tR = $_POST['treatment'];
$sql = "UPDATE tbl_Animals SET animal_Type = '$tP', animal_Breed = '$bR', animal_Gender = '$gE', animal_Injuries = '$iN', animal_Treatments = '$tR' WHERE animal_Name = '$nM'";
echo "test: " . $nM . $tP . $bR . $gE . $iN . $tR;
mysql_query($sql,$con) or die("error: " . mysql_error());
mysql_close($con)
?>
Executing the asynctask in my update button:
public void Update(View v)
{
new UpdateAnimalTask().execute();
}
The android code is not breaking so I suspect it's something with the php because my toast pops up that says update successful in my onPostExecute.
Thank you in advance.