1

I am simply trying to insert data from android code to mysql database using php but the code does not do anything.

register.php:

<?php

// array for JSON response
$response = array();

 // check for required fields

if (isset($_POST['n'])) 
{  

$name = $_POST['n'];
$address = $_POST['add']; 
//$age = $_POST['age'];
$phone = $_POST['phone'];
$email = $_POST['e'];  
$bloodgroup = $_POST['bloodgroup'];  


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

   // mysql inserting a new row
$result = mysql_query("Insert into bloodtb(Name,Address,Phone,Email,Bloodgroup) values

('$name','$address','$phone','$email','$bloodgroup')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
} 
?>

register.java:

public class register extends Activity
{

EditText name,address,bg,ph,email,age;
Button register;


private ProgressDialog pDialog;
int flag=0;
JSONParser jsonParser = new JSONParser();
private static String url = "http://192.168.43.41/phpfiles/register.php";
private static final String TAG_SUCCESS = "success";

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    name=(EditText)findViewById(R.id.etname);
   // age=(EditText)findViewById(R.id.etage);
    address=(EditText)findViewById(R.id.etadd);
    bg=(EditText)findViewById(R.id.etbg);
    email=(EditText)findViewById(R.id.etemail);
    ph=(EditText)findViewById(R.id.etphone);


    register=(Button)findViewById(R.id.btnreg);

    register.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View view){

         new Thread(new Runnable() {
              @Override
              public void run() {
                  new loginAccess().execute();                  }
          });

        }
    });

   } 

class loginAccess extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(register.this);
        pDialog.setMessage("Registering..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected String doInBackground(String... arg0) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        String n=name.getText().toString();
        //String a=age.getText().toString();
        String add=address.getText().toString();
        String e=email.getText().toString();
        String phone=ph.getText().toString();
        String bloodgroup=bg.getText().toString();


        params.add(new BasicNameValuePair("n", n));
       // params.add(new BasicNameValuePair("age", a));
        params.add(new BasicNameValuePair("add",add));
        params.add(new BasicNameValuePair("phone",phone));
        params.add(new BasicNameValuePair("e", e));
        params.add(new BasicNameValuePair("bloodgroup",bloodgroup));

        JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);

        Log.d("Create Response", json.toString());

        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1)
            {
                flag=0;
                //Intent i = new Intent(getApplicationContext(),search.class);
                /*i.putExtra("mobile_number",number);
                i.putExtra("password",pwd);*/
                //startActivity(i);
                finish();
            }
            else
            {
                // failed to Sign in
               flag=1;
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        if(flag==1)
            Toast.makeText(register.this,"Please Enter Correct informations", Toast.LENGTH_LONG).show();

    }

}


}

there is no error in the log cat but still nothing is being inserted into the database..Please help.

Achra
  • 57
  • 1
  • 9
  • was it successfull or no? – Rod_Algonquin Jun 10 '14 at 06:33
  • can you see in apache access logfile that your php script is called? Any messages in apache/php error logfile? – Jens Jun 10 '14 at 06:35
  • the activity runs on a device but nothing happens on clicking the register button. – Achra Jun 10 '14 at 06:38
  • `Oops! An error occurred` is not an error that tells you anything. Try `mysql_error()` – Hanky Panky Jun 10 '14 at 06:39
  • http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Hanky Panky Jun 10 '14 at 06:40
  • yes it is there in the apache access logfile..and no error in access/php error logfile.. – Achra Jun 10 '14 at 06:45
  • Whether you are trying to access the URL in android emulator or mobile device? – Thaangaraj Jun 10 '14 at 06:55
  • I am running it on mobile device. – Achra Jun 10 '14 at 06:57
  • Ok, then directly type this URL "http://192.168.43.41/phpfiles/" in the browser. If you get response from PHP server, then both are in same network. So problem with our android code. If you not received response in our browser then PHP server & mobile device not in same network. – Thaangaraj Jun 10 '14 at 07:01
  • why is there nothing happening on clicking a button..no action is being performed,not even a toast is being displayed on clicking a button..can anyone help? – Achra Jun 10 '14 at 07:12
  • @Achra did u tried with your mobile browser? – Thaangaraj Jun 10 '14 at 07:15
  • @Thaangaraj when i run this url(192.168.43.41/phpfiles/register.php) on my laptop browser i am getting the following response: {"success":0,"message":"Required field(s) is missing"} – Achra Jun 10 '14 at 07:26
  • @Achra I'm asking on our mobile browser. May be you mobile and laptop in different network. So you will not access it by using the ip address u have mentioned. So Check it on mobile browser and respond – Thaangaraj Jun 10 '14 at 07:28
  • @Thaargaraj when i run it on mobile device then also i am getting the same response as in browser..So i guess there is no network issues.. – Achra Jun 10 '14 at 07:46

1 Answers1

0

you are not starting the thread so your code is not executed at all

new Thread(new Runnable() 
{
     @Override
     public void run() 
     {
          new loginAccess().execute();                  
     }
 }).start();

AsyncTask is also executed on different thread so even below code should execute you task

new loginAccess().execute();
Syed Waqas
  • 862
  • 2
  • 9
  • 29
  • when i add .start(); then i am getting an error:java.lang.ExceptionInInitializerError at com.blood.bloodconnect.register$1$1.run(register.java:59) at java.lang.Thread.run(Thread.java:1096) Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.(Handler.java:121) at android.os.AsyncTask$InternalHandler.(AsyncTask.java:421) – Achra Jun 10 '14 at 07:48
  • as I said it in my answer AsyncTask runs in its own thread you don't need to start it in within another thread just use new loginAccess().execute(); – Syed Waqas Jun 10 '14 at 07:49