Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to insert data into mysql and its shows "data inserted successfully" but blank row inserted in mysql and for that I have DEBUG and found that Volley stringRequest is Null. I think Parameter is NULL in such case how to deal please suggest.


my code is belwo

PHP
<pre><?php

include 'DatabaseConfig.php' ;
 
 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
 
  $f_name = false;
 if(isset($_POST['name'])){
     $f_name = $_POST['name'];

}
echo $f_name;

$l_name = false;
if(isset($_POST['fname'])){
     $l_name = $_POST['fname'];

}
echo $l_name;

    
 
   
 
 $Sql_Query = "insert into dajs (name,fname) values ('$f_name','$l_name')";
 
 if(mysqli_query($con,$Sql_Query)){
 
 echo 'Data Inserted Successfully';
 
 }
 else{
 
 echo 'Try Again';
 
 }
 mysqli_close($con);
?>



and my java code is below

Java
<pre>package com.example.digitalrukhivalmikisamaj;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.Button;

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

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;



public class applicationform extends AppCompatActivity {

    TextView tv;

    // Creating EditText.
    EditText FirstName, LastName ;

    // Creating button;
    Button InsertButton;

    // Creating Volley RequestQueue.
    RequestQueue requestQueue;

    // Create string variable to hold the EditText Value.
    String FirstNameHolder, LastNameHolder;

    // Creating Progress dialog.
    ProgressDialog progressDialog;

    // Storing server url into String variable.
    String HttpUrl = "https://dajsapp.000webhostapp.com/get_data1.php";

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

        tv=findViewById(R.id.ttppl);
        tv.setText("ડિજિટલ ગુજરાતી અનુસૂચિત\n જાતિ સમાજ એપ ");

        // Assigning ID's to EditText.
        FirstName = (EditText) findViewById(R.id.name);
        LastName = (EditText) findViewById(R.id.fname);

        // Assigning ID's to Button.
        InsertButton = (Button) findViewById(R.id.btn1);

        // Creating Volley newRequestQueue .
        requestQueue = Volley.newRequestQueue(applicationform.this);

        progressDialog = new ProgressDialog(applicationform.this);

        // Adding click listener to button.
        InsertButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Showing progress dialog at user registration time.
                progressDialog.setMessage("Please Wait, We are Inserting Your Data on Server");
                progressDialog.show();

                // Calling method to get value from EditText.
                GetValueFromEditText();



                // Creating string request with post method.
                StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String ServerResponse) {

                                // Hiding the progress dialog after all task complete.
                                progressDialog.dismiss();

                                // Showing response message coming from server.
                                Toast.makeText(applicationform.this, ServerResponse, Toast.LENGTH_LONG).show();
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {

                                // Hiding the progress dialog after all task complete.
                                progressDialog.dismiss();

                                // Showing error message if something goes wrong.
                                Toast.makeText(applicationform.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected Map<String, String> getParams() {

                        // Creating Map String Params.
                        Map<String, String> params = new HashMap<String, String>();

                        // Adding All values to Params.
                        params.put("first_name", FirstNameHolder);
                        params.put("last_name", LastNameHolder);

                        return params;
                    }

                };


                // Creating RequestQueue.
                RequestQueue requestQueue = Volley.newRequestQueue(applicationform.this);

                // Adding the StringRequest object into requestQueue.
                requestQueue.add(stringRequest);

            }
        });


    }

    // Creating method to get value from EditText.
    public void GetValueFromEditText(){

        FirstNameHolder = FirstName.getText().toString().trim();
        LastNameHolder = LastName.getText().toString().trim();
        


    }




}



So finally from DEBUG Its a Volley stringRequest Parameter send NULL Please suggest how to overcome from this issue.

What I have tried:

I have searched many blog but not find any perfect idea hence I am here for seeking help.
Posted
Updated 21-May-22 1:56am
v3
Comments
Mohibur Rashid 2-Dec-19 1:28am    
Your parameter in java application is first_name and last_name but in your PHP script it is fname and lname
MAHESH WAGHELA 2-Dec-19 2:15am    
I have changed it in PHP but result is same.
Mohibur Rashid 2-Dec-19 2:22am    
can you also update this question?

And also

print your query in a log file and try running the query in the cli

Also log $_SERVER to get if you are getting request properly

Log $_POST by print_r

And finally write a html form with post method with the similar field and try to submit and see it it workds
MAHESH WAGHELA 2-Dec-19 2:50am    
I have updated my question and you can see my logcat File

Not a solution, but a serious problem you need to fix through your whole app: Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 
Comments
MAHESH WAGHELA 2-Dec-19 2:19am    
Accept your suggestion but it's not my question solution if you know the solution of my question then please reply
OriginalGriff 2-Dec-19 2:26am    
Your question can wait: if you don't go through your whole app and fix that, you will have much bigger problems than a small bug in a simple piece of code ...

I'm a bit late to answer this, but I think it may help someone facing same problem.
I search through all similar questions on SO, relating to PHP and Volley api but I didn't find any satisfying answer.

The problem is that you are sending data from the Volley library as content type

application/json

but your PHP script is expecting POST data as content type

application/x-www-form-urlencoded

In your PHP script, do this:

PHP
$_POST = json_decode(file_get_contents('php://input'), true); //--the miss part in your php script. put this line before $f_name = false;
    
    if ( !empty($_POST['name']) ) {

        $name = $_POST['name'];
        echo $name;
    }


Now if you check for

PHP
if( isset($_POST['name']) ){

    echo "something";
}


it should work now
 
Share this answer
 
v2

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