0

Below is the PHP code. The code is meant to display all from a table where the username equals a value from android. When I run this in postman using both get and post this works fine and returns the JSON as such.

require_once 'connection.php';

class Get_game
{

    private $db;
    private $connection;

    function __construct()
    {

        $this->db = new DB_Connection();
        $this->connection = $this->db->get_connection();

    }

    public function get_game_id($username)
    {

        //$query = "select * from volley";
        $query = "select * from volley WHERE username = '".$username."'";


        $result = mysqli_query($this->connection, $query) or die ("Error in Selecting " . mysqli_error($this->connection));

        //create an array
        $emparray = array();
        while ($row = mysqli_fetch_assoc($result)) {
            $emparray = $row;
        }

        $data = array('Game_ids' => $emparray);
        echo json_encode( $data);

        //close the db connection
        mysqli_close($this->connection);



    }
}




$game = new Get_game();

if (isset($_GET['username'])) {
    $username = $_GET['username'];

    if (!empty($username)) {
        $game->get_game_id($username);
    } else {
        echo("error");
    }

}

However, when I try to run on the Android side of things the code will not display. I have played around with get and post but nothing seems to work. Below is the android code.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;

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

import static com.android.volley.Request.*;


public class MainActivity extends AppCompatActivity {
    // Will show the string "data" that holds the results
    TextView results;
    // URL of object to be parsed
    String JsonURL = "http://192.168.0.14/simplifiedcoding/volleyRegister.php";
    // This string will hold the results
    String data = "";
    // Defining the Volley request queue that handles the URL request concurrently
    RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Creates the Volley request queue
        requestQueue = Volley.newRequestQueue(this);

        // Casts results into the TextView found within the main layout XML with id jsonData
        results = (TextView) findViewById(R.id.jsonData);

        // Creating the JsonObjectRequest class called obreq, passing required parameters:
        //GET is used to fetch data from the server, JsonURL is the URL to be fetched from.
        JsonObjectRequest obreq = new JsonObjectRequest(Method.POST, JsonURL, null,
                // The third parameter Listener overrides the method onResponse() and passes
                //JSONObject as a parameter
                new Response.Listener<JSONObject>() {

                    // Takes the response from the JSON request
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONObject obj = response.getJSONObject("Game_ids");
                            // Retrieves the string labeled "colorName" and "description" from
                            //the response JSON Object
                            //and converts them into javascript objects
                            String id = obj.getString("id");
                            String username = obj.getString("username");
                            String password = obj.getString("password");
                            String email = obj.getString("email");

                            // Adds strings from object to the "data" string
                            data += "Color Name: " + id +
                                    "nDescription : " + username + "pass" + password + "email" + email;

                            // Adds the data string to the TextView "results"
                            results.setText(data);
                        }
                        // Try and catch are included to handle any errors due to JSON
                        catch (JSONException e) {
                            // If an error occurs, this prints the error to the log
                            e.printStackTrace();
                        }
                    }
                },
                // The final parameter overrides the method onErrorResponse() and passes VolleyError
                //as a parameter
                new Response.ErrorListener() {
                    @Override
                    // Handles errors that occur due to Volley
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", "Error");
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> hashMap = new HashMap<String, String>();
                String username = "cmac";
                hashMap.put("username", username);

                return hashMap;
            }
        };

        // Adds the JSON object request "obreq" to the request queue
        requestQueue.add(obreq);
    }
}
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
cmc12345
  • 9
  • 6
  • 1
    The Java is sending a `POST` not a `GET` , which is what the PHP is asking for. When it sends the request, `if (isset($_GET['username'])) {` skips and the only thing that happens is a database connection opens – IsThisJavascript Aug 15 '17 at 15:53
  • If i change the $_get to $_post in my php file though it doesnt return the json? – cmc12345 Aug 15 '17 at 15:54
  • when i change the java to POST i still dont get the json intot he android code – cmc12345 Aug 15 '17 at 15:56
  • Put a `print_r($_POST)` somewhere at the end of your script and see if you're actually getting post data. Then debug your SQL if you do get correct POST values. Your query is also vulnerable to mysql injection attacks, you ought to read up on prepared statements – IsThisJavascript Aug 15 '17 at 15:57
  • print_r($_POST) doesn't show anything? I have read up but this is just for a small school project so its not a big worry about the inject attack – cmc12345 Aug 15 '17 at 16:00
  • 1
    Its home time for me. Go into your onResponse function and see if you can print out the response. Right now with your code you won't see an output because you're looking for a specific json result. – IsThisJavascript Aug 15 '17 at 16:02
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Aug 15 '17 at 17:36

0 Answers0