I try to update two records at the same time in android studio and php pdo

0

I have a table with the fields Id, backup, family. What I'm trying to do is update a family record that matches the backup because they have the same value and at the time of updating the two values are updated both backup and of family.

Annex my PHP code.

<?php 
 require('conexion.php');

   $respaldo=$_POST['respaldo'];

    // Consulta de Usuarios en la base de  datos
      $consulta = "SELECT *
                         FROM tb_familia
                         WHERE respaldo= ?";
      $comando=$conn->prepare($consulta);
      $comando->execute(array($respaldo));
      $row=$comando->fetch(PDO::FETCH_ASSOC);

       if($row)
       {

        $respaldo=$_POST['respaldo'];
        $familia =$_POST['familia'];
        $code=$_POST['respaldo'];

    // Creando consulta UPDATE
    $consulta = "UPDATE tb_familia" .
        " SET respaldo=?,familia=?" .
        "WHERE respaldo=?";

     // Preparar la sentencia
    $cmd = $conn->prepare($consulta);

     // Relacionar y ejecutar la sentencia
    $cmd->execute(array($code,$familia,$respaldo));
    print json_encode(
        array(
            'estado' => '1',
            'mensaje' => 'Se actualizó  correctamente')
    );

      }
      else
      {
          print json_encode(
        array(
            'estado' => '2',
            'mensaje' => 'No se actualizó  por que no existe  un registro con este  código')
    );
 }
 ?>

ANDROID CODE (JAVA) TO UPDATE RECORDS.

  private void submitForm() {
    ActualizarFamilia(
            spbuscarfamilia.getSelectedItem().toString(),
            updaterespaldo.getText().toString(),
            etmodificacion.getText().toString()
    );
}

private void ActualizarFamilia(final String respaldo, final String code, final String familia ) {
    // Tag used to cancel the request
    String cancel_req_tag = "register";
    showLoadingDialog("Espere Actualizando ......");
    StringRequest strReq = new StringRequest(Request.Method.POST,
            Config.URL_UPDATE_FAMILIA, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Register Response: " + response.toString());

            try {
                hideLoadingDialog();
                JSONObject jObj = new JSONObject(response);
                String estado = jObj.getString("estado");

                if (estado.equalsIgnoreCase("1")) {
                    Toast toast1 = Toast.makeText(updateFamilia.this," Actualización  en Familia  con  éxito",Toast.LENGTH_LONG);
                    TextView v=(TextView)toast1.getView().findViewById(android.R.id.message);
                    v.setShadowLayer(0,0,0,Color.YELLOW);
                    v.setBackgroundColor(Color.GREEN);
                    v.setTextColor(Color.BLACK);
                    v.setTextSize(20);
                    toast1.setGravity(Gravity.CENTER | Gravity.CENTER,0,0);;
                    toast1.show();
                    Limpiar();
                    submitbitacoraActualizacionFamilia();

                } else {
                    hideLoadingDialog();
                    Toast toast2= Toast.makeText(updateFamilia.this,"No se Actualizó  por que no existe  Familia con este Id",Toast.LENGTH_LONG);
                    TextView v=(TextView)toast2.getView().findViewById(android.R.id.message);
                    v.setShadowLayer(0,0,0,Color.YELLOW);
                    v.setBackgroundColor(Color.RED);
                    v.setTextSize(20);
                    toast2.setGravity(Gravity.CENTER | Gravity.CENTER,0,0);
                    toast2.show();
                    Limpiar();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Registration Error: " + error.getMessage());
            Toast toast3=  Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG);
            toast3.setGravity(Gravity.CENTER| Gravity.CENTER,0,0);
            toast3.show();
            hideLoadingDialog();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("respaldo",respaldo);
            params.put("respaldo",code);
            params.put("familia",familia);
            return params;
        }
    };
    // Adding request to request queue
    AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}


public void showLoadingDialog(String texto) {
    try {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.setMessage(texto);
        progressDialog.show();
    } catch (Exception exception) {
        progressDialog = null;
    }

}

public void hideLoadingDialog() {
    try {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    } catch (Exception a) {
        progressDialog = null;
    }
}

private void confirmUpdateFamilia(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("Está  seguro  que quiere Actualizar en Familia?");

    alertDialogBuilder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    submitForm();

                }
            });

    alertDialogBuilder.setNegativeButton("No",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    Limpiar();
                }
            });

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

// INSERCIÓN EN BITÁCORA DE ACTUALIZACIÓN
private void submitbitacoraActualizacionFamilia() {
    InsertarbitacoraActualizacionFamilia(
            muestramensaje.getText().toString(),
            muestrausuario.getText().toString(),
            muestrafecha.getText().toString(),
            muestrahora.getText().toString()
    );
}

private void InsertarbitacoraActualizacionFamilia(final String Accion_Ralizada,  final String Usuario_ingreso, final String Fecha,final String hora) {
    // Tag used to cancel the request
    String cancel_req_tag = "register";

    StringRequest strReq = new StringRequest(Request.Method.POST,
            Config.URL_ADD_BITACORA, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Register Response: " + response.toString());

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error al registrar: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("Accion_Realizada",Accion_Ralizada);
            params.put("Usuario_ingreso",Usuario_ingreso);
            params.put("Fecha",Fecha);
            params.put("hora",hora);
            return params;
        }
    };
    // Adding request to request queue
    AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}

public void Limpiar(){
    spbuscarfamilia.setSelection(0);
    etmodificacion.setText("");
}
public void onBackPressed() {

    return;
    }
  }

Variable where I capture the same family value to pass the same value to backup.

            updaterespaldo=(EditText)findViewById(R.id.etrespaldo) ;
            String modify=etmodificacion.getText().toString();
            updaterespaldo.setText(modify);
    
asked by Sofia 31.10.2017 в 18:52
source

1 answer

0

At first glance I see two errors in your code.

1st error

A space is missing in your update query:

$consulta = "UPDATE tb_familia" .
        " SET respaldo=?,familia=?" .
        "WHERE respaldo=?";
         ^aquí

Currently, it is constructed like this:

UPDATE tb_familia SET respaldo=?,familia=?WHERE respaldo=?
                                          ^¡ERROR!

It should be:

$consulta = "UPDATE tb_familia" .
        " SET respaldo=?,familia=?" .
        " WHERE respaldo=?";

2nd error

You are sending the respaldo key twice from Android:

        Map<String, String> params = new HashMap<String, String>();
        params.put("respaldo",respaldo);
        params.put("respaldo",code);
        params.put("familia",familia);

No doubt that this will bring you problems or possible erroneous data ... How will PHP know what is the value of respaldo and what is the% of code ?

It should be:

        Map<String, String> params = new HashMap<String, String>();
        params.put("respaldo",respaldo);
        params.put("code",code);
        params.put("familia",familia);

And, consequently, modify this line in PHP:

    $code=$_POST['respaldo'];

for this:

    $code=$_POST['code'];

As it was before, if it works, $code would be taking the value of the first element of the Map passed from Android.

  

Although I wonder if what you want to filter there is not the value of the   column id ¿?

Another recommendation

Apart from those errors, it is always good to control your PHP code: that the connection is not null, that the statement is well prepared, etc., etc. and go building a suitable answer json to read it on Android, so that the App does not crack ever, even if there is a server-side error. With your current code, it is possible that if the connection to the bd is not available at that moment or if something else is not controlled, the app will exit unexpectedly, causing a bad user experience.

    
answered by 31.10.2017 в 20:09