Search code examples
phpandroidmysqldatabasewebrequest

Add data to mysql database with web request Android


I'm currently working on a project where I have to add data to a mysql database. I use Microsoft Azure as my host and everything is working fine. The only problem I get is that when I try to add data using a 'Post' web request I get no errors but nothing is added.

Here is my code on Android Studio, again no errors whatsoever:

package com.example.antoinedepommereau.livre;



public class Login extends AppCompatActivity {

public static Dialog mydiag;
public static Button SignUpButton;
public static EditText firstnameTxt;
public static EditText lastnameTxt;
public static EditText emailsignupTxt;
public static EditText passwordsignupTxt;
public static EditText confirmpasswordTxt;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_login);

    Button LoginButton = (Button) findViewById(R.id.btn_login);

    final TextView SignUpText = (TextView) findViewById((R.id.link_signup));
    final EditText emailTxt = (EditText)findViewById(R.id.input_email);
    final EditText passwordTxt = (EditText)findViewById(R.id.input_password);


    SignUpText.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            showDialog();
        }
    });

    LoginButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            if("".equals(emailTxt.getText().toString())){
                emailTxt.setError("Email adress is required!");
                return;                }

            if("".equals(passwordTxt.getText().toString())){
                passwordTxt.setError("Password is required!");
                return;
            }

           /* Intent startActivitylivre = new Intent(Login.this, livremain.class);
            startActivity(startActivitylivre);*/
        }
    });

}

private void showDialog()
{
    final Dialog mydiag = new Dialog(this);

    //set the title
    mydiag.setTitle("Sign Up");

    //inflate the layout
    mydiag.setContentView(R.layout.fragment_sign_up);

    mydiag.show();

    SignUpButton = (Button) mydiag.findViewById(R.id.btn_signup);
    firstnameTxt = (EditText)mydiag.findViewById(R.id.login_firstname);
    lastnameTxt = (EditText)mydiag.findViewById(R.id.login_lastname);
    emailsignupTxt = (EditText)mydiag.findViewById(R.id.login_email);
    passwordsignupTxt = (EditText)mydiag.findViewById(R.id.login_password);
    confirmpasswordTxt = (EditText)mydiag.findViewById(R.id.login_passwordconfirm);

    SignUpButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            if ("".equals(firstnameTxt.getText().toString())) {
                firstnameTxt.setError("Your first name is required!");
                return;
            }

            if ("".equals(lastnameTxt.getText().toString())) {
                lastnameTxt.setError("Your last name is required!");
                return;
            }

            if ("".equals(emailsignupTxt.getText().toString())) {
                emailsignupTxt.setError("You must enter a valid email adress!");
                return;
            }

           /* if(passwordsignupTxt.getText().toString() != confirmpasswordTxt.getText().toString()){
                confirmpasswordTxt.setError("Passwords are not matching");
                return;
            }*/
            try {
                getText();
            }

            catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Url expection!", Toast.LENGTH_LONG).show();
            }
        }
    });
}


public void getText () throws UnsupportedEncodingException{

    String name = firstnameTxt.getText().toString();
    String email = emailsignupTxt.getText().toString();
    String password = confirmpasswordTxt.getText().toString();

    String data = URLEncoder.encode("Name", "UTF-8")
            + "=" + URLEncoder.encode(name, "UTF-8");

    data += "&" + URLEncoder.encode("Email", "UTF-8") + "="
            + URLEncoder.encode(email, "UTF-8");

    data += "&" + URLEncoder.encode("Password", "UTF-8")
            + "=" + URLEncoder.encode(password, "UTF-8");

    String text = "";
    BufferedReader reader=null;

    // Send data
    try
    {

        // Defined URL  where to send data
        URL url = new URL("http://hitachipick.azurewebsites.net/SQLQuery.php");

        // Send POST data request

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write( data );
        wr.flush();

        // Get the server response

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            // Append server response in string
            sb.append(line + "\n");
        }


        text = sb.toString();
    }
    catch(Exception ex)
    {

    }
    finally
    {
        try
        {

            reader.close();
        }

        catch(Exception ex) {}
    }

    confirmpasswordTxt.setText(text);
}

}

And then my PHP code:

 <?php
 $servername = "eu-cdbr-azure-north-e.cloudapp.net";
 $username = "bdbad7b3d3b2da";
 $password = "39d98912";
  try 
 { 
      $conn = new PDO("mysql:host=$servername;dbname=Hitachi",$username, 
      $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      echo "connected succesfully";
 }
 catch(PDOException $e)
 {
      echo "Connection failed: " . $e->getMessage();
 }  

 if (isset($_POST['Name']) && isset($_POST['Email']) &&  
 isset($_POST['Password'])){
//Insert new contact into database
$query = $conn->prepare('INSERT INTO contact_info (contact_name, 
contact_email, contact_password) VALUES (:name, :email, :password)');
$query->execute([
    ':name' => $_POST['Name'],
    ':email' => $_POST['Email'],
    ':password' => $_POST['Password']
]); 
echo"done";
}
?>

The connection to the database is working fine as I get "connected succesfully" but nothing is added to the database. I don't know where the problem is coming from.

Hope you can help,

Thanks for your help.

EDIT:

I'm now using Ravi's code:` String urlParameters = "Name="+name+"&Email="+email+"&Password"+password;

        byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
        int    postDataLength = postData.length;

        String request        = "http://hitachipick.azurewebsites.net/SQLQuery.php";
        URL    url            = new URL( request );
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setDoOutput( true );
        conn.setInstanceFollowRedirects( false );
        conn.setRequestMethod( "POST" );
        conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty( "charset", "utf-8");
        conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
        conn.setUseCaches( false );
        try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
            wr.write( postData );
            Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
        }`

But it's still not working.... I've added a catch to see the error in the log-cat:

android.os.NetworkOnMainThreadException
                                                                                        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                                                                                        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
                                                                                        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
                                                                                        at java.net.InetAddress.getAllByName(InetAddress.java:752)
                                                                                        at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
                                                                                        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:209)
                                                                                        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:163)
                                                                                        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:105)
                                                                                        at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:489)
                                                                                        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:465)
                                                                                        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371)
                                                                                        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:503)
                                                                                        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:130)
                                                                                        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:261)
                                                                                        at com.example.antoinedepommereau.livre.Login.getText(Login.java:173)
                                                                                        at com.example.antoinedepommereau.livre.Login$3.onClick(Login.java:134)
                                                                                        at android.view.View.performClick(View.java:6261)
                                                                                        at android.widget.TextView.performClick(TextView.java:11185)
                                                                                        at android.view.View$PerformClick.run(View.java:23752)
                                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

I am really stuck,, pleasse hellpp...


Solution

  • If var_dump($POST) prints null, which means, you have issue when your request is getting constructed.

    Also, I noticed, you haven't specify the request type in your code. So, probably just specify

    conn.setRequestMethod( "POST" );
    

    If still doesn't work, Then, use below code, which working for me.

    // specify parameter and their value
    String urlParameters  = "param1=a&param2=b&param3=c";
    
    byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
    int    postDataLength = postData.length;
    
    String request        = "http://hitachipick.azurewebsites.net/SQLQuery.php";
    URL    url            = new URL( request );
    HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
    conn.setDoOutput( true );
    conn.setInstanceFollowRedirects( false );
    conn.setRequestMethod( "POST" );
    conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
    conn.setRequestProperty( "charset", "utf-8");
    conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
    conn.setUseCaches( false );
    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
       wr.write( postData );
    }