0

I'm a beginner. I'm trying to insert data from android to MySQL using php. But it doesn't add rows to the database.

u_data_insert.php :

<?php
$servername = "localhost";
$username = "zprestau01u";
$password = "ZPrestau#01U$100";
$dbname = "zprestau01";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$username=$_POST['Name'];
$email = $_POST['Email'];
$password = $_POST['Password'];


$sql = "INSERT INTO demotable(Name,Email,Password) VALUES ('$username','$email','$password')";


if(mysqli_query($conn,$sql)){

 echo 'Data Submit Successfully';

 }
 else{

 echo "Error:".mysqli_error($conn);

 }
 mysqli_close($conn);
?>

BackgroundTask.java

public class BackgroundTask extends AsyncTask<String,Void,String> {

    Context ctx;
    BackgroundTask(Context ctx)
    {
        this.ctx=ctx;
    }


    protected String doInBackground(String... params) {

        String reg_url="http://restaurant.zpcoder.mobi/u_data_insert.php";
        String method=params[0];
        String text = "";
        if(method.equals("register"))
        {
            String name=params[1];
            String email = params[2];
            String password=params[3];

            try {
                URL url=new URL(reg_url);
                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream os=httpURLConnection.getOutputStream();

                String data= URLEncoder.encode("Name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
                        URLEncoder.encode("Email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"+
                        URLEncoder.encode("Password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
                BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
                bufferedWriter.write(data);
                bufferedWriter.flush();
                int statusCode = httpURLConnection.getResponseCode();
                if (statusCode == 200) {

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

                    while ((line = reader.readLine()) != null)
                        sb.append(line).append("\n");

                    text = sb.toString();
                    bufferedWriter.close();
                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return text;
    }

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

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

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

RegActivity.java :

regRegister.setOnClickListener(new View.OnClickListener()

                {


                    @Override
                    public void onClick(View view) {


                        String method="register";
                        BackgroundTask backgroundTask=new BackgroundTask(RegActivity.this);
                        backgroundTask.execute(method,Name,Email,Password);
                        finish();
                    }


                });


            }

        });

It is supposed to make a Toast with "Data Submit Successfully", but it shows "Try Again" and doesn't add a new row in MySQL Database. Could you please tell me where have I done wrong?

Munem Sohan
  • 41
  • 1
  • 1
  • 11

1 Answers1

1

When you pass the fields - I think they are called name, password & contact...

String data= URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
    URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"+
    URLEncoder.encode("contact","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");

But when you read them in PHP they are called - Name, Email and Password

$username=$_POST['Name'];
$email = $_POST['Email'];
$password = $_POST['Password'];

They should use the same names in both parts of your code.

You also need to ensure that you check your variables names as your define $sql and then use $Sql.

Especially while your getting things to work, you would benefit to output the error if your SQL fails. So instead of...

 echo 'Try Again';

Have something like...

echo "Error:".mysqli_error($conn);

Update: To help debugging...

echo "SQL=".$sql. " Error:".mysqli_error($conn);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • I have done everything as you have instructed. But Still it shows: Duplicate entry '' for key 'Name'. By the way, in the DB, "Name' is a unique key, but after using different values for Name, it shows that error. – Munem Sohan Mar 18 '18 at 08:01
  • Can you change that error line to the one added to answer - see what SQL it's trying to run. – Nigel Ren Mar 18 '18 at 08:06
  • it shows: SQL = INSERT INTO demotable (Name, Email, Password) VALUES (",",") Error: Duplicate entry " for key 'Name' – Munem Sohan Mar 18 '18 at 08:11
  • So either the parameters aren't being sent or they aren't getting to your PHP script. Not sure how Java passed data perhaps https://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post may help. – Nigel Ren Mar 18 '18 at 08:16