Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi I am using Volley Library in android app and the api is coded in PHP and database is MySql. I have checked the api code in PostMan and its working fine but when I insert data from android app , it causes duplicate insertion of record in mysql database.I can not find out the where is the problem.

What I have tried:

<?php

require_once 'DB/DBConnect.php';

$db=new DBConnect();
$pdoObj=$db->connectToDB();

$response=array();



include_once ('SanitizerClass/SanitizerClass.php');

$userType = $_POST['UserType_Key'];
$userName =SanitizerClass::sanitizeUsername($_POST['UserName_Key']);
$email = SanitizerClass::sanitizeEmail($_POST['Email_Key']);
$mobile=trim($_POST['Mobile_Key']);
$plain_password=$_POST['Password1_Key'];
$encrypted_password = password_hash($plain_password,PASSWORD_BCRYPT);
$pwd2=$_POST['Password2_Key'];
$isEmailVerified="NotVerified";
$generated_activationCode =mt_rand(1000,9999);//md5(uniqid(rand()).time());
$dateRegistered=date('d-m-Y H:i:s');

include_once 'inc/crud.php';
$ip=crud::getVisitorIP();

list($CountryName,$CityName,$ContinentName,$CurrencySymbol,$CurrencyCode,$TimeZone)=CRUD::getVisitorsDetails($ip);//here 47.9.193.174 should be changed to $ip




//check user email whether its already regsitered

$query = $pdoObj->prepare( "SELECT email FROM tbl_users WHERE email = '$email'" );

$query->execute();
$count=$query->rowCount();


//If num is bigger than 0, the email already exists and do not insert.
if($count !=0)
{

    $response['success']=0;
    $response['message']="You are already registered with this email.";
    echo json_encode($response);
    /* exit; */

}
else
{
    //register
    $stmt = $pdoObj->prepare("INSERT INTO tbl_users(userType,userName,email,mobile,password,isEmailVerified,activationCode,dateRegistered,ipAddress,countryName,cityName,continent,currencySymbol,currencyCode,timeZone) 
            VALUES (:userType,:userName,:email,:mobile,:encrypted_password,:isEmailVerified,:activation_code,:dateRegistered,:ipAddress,:countryName,:cityName,:continent,:currencySymbol,:currencyCode,:timeZone)");
    $stmt->bindparam(":userType", $userType);
    $stmt->bindparam(":userName", $userName);
    $stmt->bindparam(":email", $email);
    $stmt->bindparam(":mobile", $mobile);
    $stmt->bindparam(":encrypted_password", $encrypted_password);
    $stmt->bindparam(":isEmailVerified", $isEmailVerified);
    $stmt->bindparam(":activation_code", $generated_activationCode);
    $stmt->bindparam(":dateRegistered", $dateRegistered);
    $stmt->bindparam(":ipAddress", $ip);
    $stmt->bindparam(":countryName", $CountryName);
    $stmt->bindparam(":cityName", $CityName);
    $stmt->bindparam(":continent", $ContinentName);
    $stmt->bindparam(":currencySymbol", $CurrencySymbol);
    $stmt->bindparam(":currencyCode", $CurrencyCode);
    $stmt->bindparam(":timeZone", $TimeZone); 
    $stmt->execute();
    if($stmt->rowCount()== 0)
    {
        $response['success'] = 1;
        $response['message'] = "Registration failed, Please try again";
        echo json_encode($response);
        /* exit; */
    }
    else if($stmt->rowCount() != 0)
    {
        $to_email = $email;
        $subject = "Email Verification OTP";
        
        $body = "Dear $userName <br><br>
        Thanks you for joining with us.<br>
        The OTP for verifying your email id is: $generated_activationCode
        </br><br><br>Thanks and Regards.<br><hr>Team Oodemy.com";

        $headers  = "From:xyz@example.com \r\n";  
        $headers .= "MIME-Version: 1.0 \r\n";  
        $headers .= "Content-type: text/html;charset=UTF-8 \r\n";  
        $headers .= "From: sender email";

        if (mail($to_email, $subject, $body, $headers)) 
        {
            $response['success']=2;
            $response['message']="You are successfully Registered./n/n We have sent an OTP to your email ID.";
            echo json_encode($response);
            /* exit; */
            
        } 
        else 
        {
            $response['success']=3;
            $response['message']="Activation Email has NOT been sent to your email id.Try Again...";
            echo json_encode($response);
              /* exit; */
            
        }
    }
        
        
    
    
}

?>

Android
package com.example.oodemy;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.pranavpandey.android.dynamic.toasts.DynamicToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;



public class Registration extends AppCompatActivity
{

    private RadioGroup radioGroup;
    private EditText etUserName,etMobile,etEmail,etPassword1,etPassword2;
    private Button btnRegister;
    String str_User_type,str_Username,str_Mobile,str_Email,str_Pwd_1,str_Pwd_2;


    Constants constant=new Constants();
    private String URL_of_Registration_API=constant.URL_of_PHP_SCRIPT_FOR_SIGNUP;;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);


        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        etUserName = (EditText)findViewById(R.id.etUserName);
        etMobile = (EditText)findViewById(R.id.etMobile);
        etEmail = (EditText)findViewById(R.id.etEmail);
        etPassword1 = (EditText)findViewById(R.id.etPassword1);
        etPassword2 = (EditText)findViewById(R.id.etPassword2);
        btnRegister=(Button)findViewById(R.id.btnRegister);

        progressDialog= new ProgressDialog(Registration.this);
        progressDialog.setTitle("Registering please wait...");
        progressDialog.setCancelable(false);

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str_USER_TYPE=str_User_type;
                str_Username=etUserName.getText().toString().trim();
                str_Email=etEmail.getText().toString().trim();
                str_Mobile=etMobile.getText().toString().trim();
                str_Pwd_1=etPassword1.getText().toString();
                str_Pwd_2=etPassword2.getText().toString();

                if (radioGroup.getCheckedRadioButtonId() == -1)
                {
                    // no radio buttons are checked
                    DynamicToast.makeError(getApplicationContext(), "Please choose what you are ? Teacher or Student.", 5000).show();
                }

                else if(etUserName.getText().toString().equals(""))
                {
                    DynamicToast.makeError(getApplicationContext(), "Enter your name.", 5000).show();
                }

                else if(etEmail.getText().toString().equals(""))
                {
                    DynamicToast.makeError(getApplicationContext(), "Enter your email.", 5000).show();
                }
                else if (doesEmailFormatCorrect(etEmail.getText().toString())==false)
                {
                    DynamicToast.makeError(getApplicationContext(), "Invalid Email Format.", 5000).show();
                }
                else if(etMobile.getText().toString().equals(""))
                {
                    DynamicToast.makeError(getApplicationContext(), "Enter your mobile number.", 5000).show();
                }
                else if(etPassword1.getText().toString().equals(""))
                {
                    DynamicToast.makeError(getApplicationContext(), "Enter password.", 5000).show();
                }
                else if(etPassword2.getText().toString().equals(""))
                {
                    DynamicToast.makeError(getApplicationContext(), "Please confirm password.", 5000).show();
                }
                else if(!etPassword1.getText().toString().equals(etPassword2.getText().toString()))
                {
                    DynamicToast.makeError(getApplicationContext(), "Both passwords do not match.", 5000).show();

                }
                else
                {
                    Register();
                }
            }
        });

    }


    private void Register()
    {
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_of_Registration_API,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("anyText",response);
                        try{
                            JSONObject jsonObject = new JSONObject(response);
                            String success = jsonObject.getString("success");
                            String message = jsonObject.getString("message");
                            if(success == "2")
                            {
                                Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
                                progressDialog.dismiss();
                                Intent login = new Intent(Registration.this,LoginActivity.class);
                                startActivity(login);
                                finish();
                            }
                            if(success.equals("0"))
                            {
                                Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
                                progressDialog.dismiss();
                            }
                            if(success.equals("1"))
                            {
                                Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
                                progressDialog.dismiss();
                            }
                            if(success.equals("3"))
                            {
                                Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
                                progressDialog.dismiss();
                            }
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),"Registration Error !1"+e,Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(),"Registration Error !2"+error,Toast.LENGTH_LONG).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String,String> params = new HashMap<>();
                params.put("UserType_Key",str_User_type);
                params.put("UserName_Key",str_Username);
                params.put("Email_Key",str_Email);
                params.put("Mobile_Key",str_Mobile);
                params.put("Password1_Key",str_Pwd_1);
                params.put("Password2_Key",str_Pwd_2);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }


    public void moveToLogin()
    {
        startActivity(new Intent(getApplicationContext(),LoginActivity.class));
        finish();
    }

    public void onRadioButtonClicked(View view)
    {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId())
        {
            case R.id.radioBtnStudent:
                if (checked)

                    str_User_type="Student";
                    break;
            case R.id.radioBtnTeacher:
                if (checked)
                    str_User_type="Teacher";
                    break;
            default:
                str_User_type="";
                break;
        }

    }
    public boolean doesEmailFormatCorrect(String email)
    {
        String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
        if (email.toString().trim().matches(emailPattern)==true)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public void openLoginScreen(View view)
    {
        moveToLogin();
    }

}
Posted
Updated 6-Jul-21 5:34am
v2
Comments
Richard Deeming 6-Jul-21 11:41am    
$query = $pdoObj->prepare( "SELECT email FROM tbl_users WHERE email = '$email'" );

That code is vulnerable to SQL Injection[^].

You already know how to use parameters, since you've used them correctly for your other query.
David Crow 6-Jul-21 23:19pm    
You need to first narrow down whether it is a Java issue or a PHP issue. In your Java code, set a breakpoint on the statement in which the PHP code is called. Now, is that breakpoint hit once or twice? If once, then you know the problem is with your PHP code. If twice, then you know the problem is with your Java code.

Check whether your android code is making multiple calls to PHP for same request. Or there is some logic issue in PHP which is causing duplicate inserts. You can easily narrow it down if you check server API call logs.
Also better to have some unique constraints in Database in addition to fixing the above problem. That keeps your data intact from corruption.
 
Share this answer
 
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900