By 2 php queries can I invoke services (json) from android?

0

I hope you can support me with this question: how to call from android 2 queries (select) in php that show the data in the app. The php code is:

    ?php $idequivalente = $_REQUEST['idequivalente2']; 
    $idUsuario2 = $_REQUEST['idUsuario2']; 
    $gasto= $_REQUEST['gasto']; 
    $con = new PDO("mysql:host=localhost; dbname=bd", "root", "123"); 
    $res=$con->query("SELECT idequivalente2,alimento,cantidad, unidad, peso, calorias FROM bdapp.tbalimentos where dequivalente2='$idequivalente'"); 
    $res2=$con->query("SELECT * FROM dieta WHERE idUsuario2='$idUsuario2' AND gasto='$gasto'"); 
    $datos=array(); 
    $datos2=array(); 
    $datos['alimentos']=$res->fetchAll(PDO::FETCH_ASSOC); 
    $datos2['dieta']=$res->fetchAll(PDO::FETCH_ASSOC); 
    echo json_encode($datos); 
    echo json_encode($datos2); 
    ?> 

When I invoke a query if it shows me the data in the app, how to invoke the second query? The code in android is this for a query:

    for (int i = 0; i < jsonArray.length(); i++) 
    { try { alimentos=new Tbalimentos(); jsonObject = jsonArray.getJSONObject(i); 
    String calorias = jsonObject.getString("calorias"); 
    System.out.println("valor: " + calorias);

FROM HERE I REALIZE THAT THIS IS BAD since when I call the CargarWS method with the two consultations, it no longer shows me any data in the app:

    private void cargarWS() {
    String url=("http://192.168.1.34:8000/ServicioWeb/Menu.php?idequivalente2="+Integer.toString(verduras.getId())+"idUsuario2="+4000+"gasto="+1393.32);
    //SE manda la info del JSON a volley para que la lea y procese la info
   jsonOR = new JsonObjectRequest(Request.Method.GET,url,null,this,this);//hace el llamado a la url x GET e intenta conectar al WS, en caso d quetodo este correcto  entra al metodo response
    request.add(jsonOR);//se agrega el json object request;permite establecer la  comunicacion con onERROR y onRESPONSE
}

If you follow this method, go to RESPONSE:

    public void onResponse(JSONObject response) {
    //----------------------SPRINNER--------------------------
    Tbalimentos alimentos= null;         
    frutasList = new ArrayList<Tbalimentos>();
    JSONArray jsonArray=response.optJSONArray("alimentos");//cogemos cada uno de los elementos dentro de la etiqueta "alimentos"
    JSONObject jsonObject;

    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            alimentos=new Tbalimentos();
            jsonObject = jsonArray.getJSONObject(i);
            String calorias = jsonObject.getString("calorias");
            System.out.println("valor: " + calorias);

            alimentos.setIdequivalente2(jsonObject.getInt("idequivalente2"));
            alimentos.setAlimento(jsonObject.getString("alimento"));
            alimentos.setCantidad(jsonObject.optString("cantidad"));
            alimentos.setUnidad(jsonObject.optString("unidad"));
            alimentos.setCalorias(jsonObject.optDouble("calorias",-1));
            frutasList.add(alimentos);
            //System.out.println("lista : " + frutasList.get(i).getIdequivalente2() + "-"+ frutasList.get(i).getAlimento());
            // frutasList.add(jsonArray.getJSONObject(i));
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }
    lista = new ArrayList<String>();
    lista.add("Seleccion");
    System.out.println("tamnano Arraglo Frutas: " + frutasList.size());

    for (int i = 0; i < frutasList.size(); i++) {//jsonArray.length()
        lista.add(frutasList.get(i).getIdequivalente2()+frutasList.get(i).getAlimento()+" "+frutasList.get(i).getCantidad()+" "+frutasList.get(i).getUnidad()+" = "+frutasList.get(i).getCalorias()+" kcal");
        System.out.println("lista : " + lista);
    }
    ArrayAdapter<CharSequence> spinnerAdapter=new ArrayAdapter(this.getActivity(), android.R.layout.simple_spinner_item, lista);
    spdesayuno1.setAdapter(spinnerAdapter);

    adapter2=new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, listaview);
    list.setAdapter(adapter2);

    spdesayuno1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            if(position!=0){ 
                Double calorias=frutasList.get(position-1).getCalorias();
                String gastoT= getArguments()!=null ? getArguments().getString("gasto5"):"SIN DATOS";
                double gastoT2 = Double.parseDouble(gastoT);//
                System.out.println("PARAMETRO: " + gastoT2);
                if(calconsumidas.equals(new Double(0))) {
                    calconsumidas = gastoT2 - calorias;
                }else{
                    calconsumidas = calconsumidas - calorias;
                }                   
                txtobjetivo.setText(gastoT2+"   -   ");
                txtcalorias.setText(calorias+"    =    ");
                txtcalconsumidas.setText(String.format("%.2f",calconsumidas));

                //paso de parametros a colacion desayuno
                args.putString("gasto6",txtcalconsumidas.getText().toString());
                fragment.setArguments(args);

                listaview.add(frutasList.get(position - 1).getAlimento() + " / "+frutasList.get(position - 1).getCantidad()+" "+frutasList.get(position - 1).getUnidad()+" / "+ frutasList.get(position - 1).getCalorias());
                System.out.println("ListView.size(): " + listaview.size());
                adapter2.notifyDataSetChanged();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });

}
    //De lo contrario entra al ERROR RESPONSE. Donde entra.
    public void onErrorResponse(VolleyError error) {
    Log.i("ERROR",error.toString());
    }
    
asked by Angelica 13.10.2017 в 03:02
source

1 answer

0

On the PHP side you can take any of the two paths.

You can have separate files and in that case from the mobile will point to two different uris depending on the webservice you want to call, for example:

www.tusitio.com/wsuno.php and www.tusitio.com/wsdos.php .

The other alternative is to have a PHP file that resolves the two web services depending on a parameter passed in the request.

The GET would be: www.tusitio.com/webservice.php?ws=wsuno and in the case of POST the url would be www.tusitio.com/webservice.php and the parameter ws=uno would be encoded within the body of the request.

In this case, in the PHP file you would lift the parameters of $_GET or $_POST and depending on the value of the parameter ws you execute one or another webservice (the query to the database and the corresponding json answer)

For information: There is one more way in which the webservice can be encoded, which is in the request path, for example www.misito.com/webservice/wsuno . This type of request is a bit more complex to implement since it is necessary to have the web server direct all the traffic to a php file that is in charge of the decoding and redirection to the program that finally ends up solving it. For this, for example, in Apache you have to add rewrite rules in the file .htaccess .

EDITION I

Suppose then that you implement the solution with GET, you would have these two urls to call from android:

www.tusitio.com/webservice.php?ws=wsuno

and

www.tusitio.com/webservice.php?ws=wsdos

Then in the php:

    <?php 
    $wsSolicitado = $_GET['ws'];

    $idequivalente = $_REQUEST['idequivalente2']; 
    $idUsuario2 = $_REQUEST['idUsuario2']; 
    $gasto= $_REQUEST['gasto']; 
    $con = new PDO("mysql:host=localhost; dbname=bd", "root", "123"); 
    $res=false;
    $datos=array();
    if($wsSolicitado == 'wsuno'){
       $res=$con->query("SELECT idequivalente2,alimento,cantidad, unidad, peso, calorias FROM bdapp.tbalimentos where dequivalente2='$idequivalente'"); 
       $datos['alimentos']=$res->fetchAll(PDO::FETCH_ASSOC);
    }else if($wsSolicitado == 'wsdos'){
       $res=$con->query("SELECT * FROM dieta WHERE idUsuario2='$idUsuario2' AND gasto='$gasto'");
       $datos['dieta']=$res->fetchAll(PDO::FETCH_ASSOC); 
    }  
    echo json_encode($datos); 

Some additional notes that are out of scope of this question:
1) Use $ _POST or $ _GET instead of $ _REQUEST
2) For the WS and especially when you send username and / or password uses $ _POST (and https).
3) Do not use dynamic sql. Use prepared statements.
4) Sanitize and validate the received parameters (in $ _POST, $ _GET, $ _REQUEST, etc) in php before using them.

    
answered by 13.10.2017 в 06:33