简体   繁体   中英

Inserting POST data in my sql using PHP

I'm trying to send some data from my android application to mysql , but only the last record which is added is added into my database . How can I add all sent data with POST into my database? This is the code i'm using from my application to send data to mysql

private void registerUser(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, 
 URL_LOGIN,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {


Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
            }
        }){
    @Override
    protected Map<String,String> getParams()throws AuthFailureError{
        Map<String,String> params = new HashMap<String, String>();
        Cursor cursor=db.rawQuery(selectQuery,null);
        if (cursor.moveToFirst()) {
            do {


                    //params.put("sid",cursor.getString(1));
                    params.put("code",cursor.getString(2));
                    params.put("answer", cursor.getString(3));





            } while (cursor.moveToNext());
        }


        return params;
    }

};

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

My PHP code :

        $answer = $_POST['answer'];
    $code = $_POST['code'];
    //$sid=$_POST['sid'];
    //$useremail = $_POST['email'];
    //$userpassword = $_POST['password'];
    $user = "root";
    $pass = "";
    $host= "localhost";
    $dbname="offlinesurvey";

    date_default_timezone_set('UTC');
    $date = date('YmdHis');
    //$name=$sid.'_'.$date;
    $con = mysqli_connect($host,$user,$pass,$dbname);


    $sql_create="CREATE TABLE   `offlinesurvey`.`lime_survey_` ( `id` INT NULL AUTO_INCREMENT ,whenadded DATETIME, `code` VARCHAR(255) NOT NULL,`answer` VARCHAR(255) NOT NULL , UNIQUE `id` (`id`)) ENGINE = MyISAM;";
    if(mysqli_query($con,$sql_create)){

    }
    else {
      "No..No";
    }
     $sql="insert into lime_survey_(whenadded,code,answer)

    (Now(),'".$code."','".$answer."');";
    if(mysqli_query($con,$sql)){
        echo  "data inserted";

    }else{
        echo "Failed";
    }

Rename your parameters to include square brackets like code[] and answer[] . Using the square brackets will turn the data in php to an array like $_POST['code'][0] for the first, etc. You can then loop over $_POST['code'] and get each value. The key for each code and answer should line up as long as there is always an answer for every code.

params.put("code[]",cursor.getString(2));
params.put("answer[]", cursor.getString(3));

Quick example of the php side:

foreach($_POST['code'] as $key=>$value){
    echo "Code {$key}: {$value}; Answer {$key}: {$_POST['answer'][$key]}\n";
}

You can also explicitly put the key number if you don't want to trust the [] appending (like if there was a missing code or answer) by renaming to something like code[0] / answer[0] , code[1] / answer[1] .

The simple fix is to make sure that each key in the Map is different. You can do that by explicitly setting the index of the key with an iterator variable like this:

@Override
protected Map<String,String> getParams()throws AuthFailureError{
    Map<String,String> params = new HashMap<String, String>();
    Cursor cursor=db.rawQuery(selectQuery,null);
    if (cursor.moveToFirst()) {
        //iterator integer
        int i = 0;
        do {
            //concatenate the iterator with the name
            params.put("code[" + String.valueOf(i) + "]",cursor.getString(2));
            params.put("answer[" + String.valueOf(i) + "]", cursor.getString(3));
            i++;
        } while (cursor.moveToNext());
    }

    return params;
}

You will still need to loop over the post data on the php side like above to get each record and insert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM