How to insert values into phpmyadmin database through android application?


#1

I have written the code to accept simple registration details from the user through an android app and store the details in phpMyadmin database. I have used Basic Activity Layout for registration screen. The registration details include: Name,Phone,Email.

When I run the application, the “Registration Success!!” message doesn’t come and data is not getting entered into the database. The register.php and init.php are created in a folder ‘webapp’ inside ‘www’ folder of ‘wamp64’ folder.

Is there any error in my code? I have beenchanging the code for so long, still I am not getting the result. I have asked many people but none of them could solve the problem. Please help me. All answers are welcome. Thank you!

(I am sorry if this post is in the wrong category.)

What I have tried:

This is my MainActivity.java file



package com.example.admin.myapplication77;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) 
    {
     Snackbar.make(view, "Replace with your own 
action",Snackbar.LENGTH_LONG).setAction("Action", null).show();
     }
    });
}

public void userReg(View view)
{
    startActivity(new Intent(this,Register.class));

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

return super.onOptionsItemSelected(item);

}
}

This is my Register.java file:


package com.example.admin.myapplication77;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;

public class Register extends AppCompatActivity {
      EditText ET_NAME,ET_PHONE,ET_EMAIL;
      String name,phone,email;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register_layout);
    ET_NAME=(EditText)findViewById(R.id.new_name);
    ET_PHONE=(EditText)findViewById(R.id.new_phone);
    ET_EMAIL=(EditText)findViewById(R.id.email);


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", 
Snackbar.LENGTH_LONG).setAction("Action", null).show();
        }
    });
    }
public void userReg(View view)
{

  name= ET_NAME.getText().toString();
  phone= ET_PHONE.getText().toString();
  email=ET_EMAIL.getText().toString();
  String method="register";
  BackgroundTask backgroundTask= new BackgroundTask(this);
  backgroundTask.execute(method,name,phone,email);
  finish();
}

}

This is my BackgroundTask.java file (to connect with database).


package com.example.admin.myapplication77;

import android.os.AsyncTask;
import android.content.Context;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLEncoder;

public class BackgroundTask extends AsyncTask<String,Void,String>{
Context ctx;
BackgroundTask(Context ctx)
{
 this.ctx=ctx;

}
@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    String reg_url="http://192.168.1.2/webapp/register.php"; 
    String method=params[0];
    if(method.equals("register"))
    {

        String name=params[1];
        String phone=params[2];
        String email=params[3];
        try {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = 
(HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new 
OutputStreamWriter(OS, "UTF-8"));
            String data= URLEncoder.encode("new_name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+URLEncoder.encode("new_phone","UTF-8")+"="+URLEncoder.encode(phone,"UTF-8")+"&"+ URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            return "Registration Success!!";
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    return null;
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
    Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}

This is my register.php file:


<?php

require"init.php";
if(isset($_GET['register'])) {
$name=$_POST["user"];
$phone=$_POST["phone"];
$email=$_POST["email"];

$sql_query="insert into user_details (Name,Phone,Email) values('$name','$phone','$email')";
if(mysqli_query($con,$sql_query))
 {
   echo "<h3>Connection Success</h3>";
 }
 else
 {
  echo "Connection Error!!".mysqli_connect_error();

 }}
 ?>

This is my init.php file to link with the database:

<?php
$db_name="webappdb";
$mysql_user="root";
$mysql_pass="root";
$server_name="localhost";

$con=mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
if(!$con)
{

 echo "Connection Error!!".mysqli_connect_error();

 }
else
{
 echo "<h3>Connection Success</h3>";
}



?>

#2

I don’t get it, you have developed a Android app with a register user form in order to save data into your local database (that you can see with PHPmyAdmin). Now the thing that I don’t understand are the php files used on this, what is their purpose?

I have done something similar for an academic project, where I use the phone GPS to track a vehicle and store them in a database (that can be either local or remote using AWS services).

Source code on Github

You can see that I use MainActivity.java to handle button actions and the background task to send the coordinates every 10 seconds, which can be seen inside BackgroundTask.java.

Everything is commented so you can understand what’s going on and what you should change in order to make it work for you.


#3

The php files are used to link the database with the application.

In BackgroundTask.java file:

String reg_url=“http://192.168.1.2/webapp/register.php”;

This line is used to denote that the file(register.php) used for registering data into database are present in my PC’s webapp folder.

This application is just to enter and retrieve data from the database.


#4

You don’t need to use php files to link the database with the Android App. I highly recommend some research about connecting to database (local or remote, doesn’t matter) using Java driver.

A nice place is StackOverflow, where you can find some post regarding to that, for example this one. Read the second one that explain the whole process step by step and you will see what you really need to do.


By the way, the url can’t help us since it is a local server (stored only on your computer files).