简体   繁体   中英

How can I pass parameters to PHP files correctly

I have problem sending a string parameter to a PHP file to download a song inserting the song's name from a edit text. I don't understand the error I'm receiving. Thanks in advance for the help!

LOGCAT:

Response from url: {"error":false,"message":"Musics fetched successfully.","musics":[]}

i don't know why the array is empty.

The PHP file works if i use a rest client passing the song's name but not in the URL. This is my code:

ANDROID SIDE:

class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
            canzone = editText.getText().toString();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            HttpHandler sh = new HttpHandler();
            // Making a request to url and getting response
            String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);


                   /* title=jsonObj.getString("title");

                    link=jsonObj.getString("link");
                    HashMap<String, String> contact = new HashMap<>();

                    contact.put("title", title);
                    contact.put("link", link);

                    System.out.println("LINK: "+link);
                    contactList.add(contact);
*/
                    Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();

                    JSONArray jsonArray = jsonObj.getJSONArray("musics");

                    for (int i = 0; i < jsonArray.length(); i++) {

                        //Declaring a json object corresponding to every pdf object in our json Array
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        //Declaring a Pdf object to add it to the ArrayList  pdfList
                        // Pdf pdf  = new Pdf();
                        // String pdfName = jsonObject.getString("name");
                        //String pdfUrl = jsonObject.getString("url");
                        //pdf.setName(pdfName);
                        //pdf.setUrl(pdfUrl);
                        //pdfList.add(pdf);
                        canzone_cantante = jsonObject.getString("canzone_cantante");

                    }

                  /*  pdfAdapter=new PdfAdapter(MainActivity.this,R.layout.list_layout, pdfList);

                    listView.setAdapter(pdfAdapter);

                    pdfAdapter.notifyDataSetChanged();*/
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("canzone_cantante", canzone_cantante);
                    //contact.put("email", email);
                    // contact.put("mobile", mobile);
                   /* Toast.makeText(getApplicationContext(),
                            "LINK: "+link ,
                            Toast.LENGTH_LONG).show();*/
                    // adding contact to contact list
                    System.out.println("LINK: " + canzone_cantante);
                    contactList.add(contact);

                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

PHP CODE:

<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){
 $canzone = $_POST['canzone'];
require_once 'dbDetails.php';
$con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die("Unable to connect");

  $sql = "SELECT * FROM music where canzone = '$canzone'";
$result = mysqli_query($con,$sql);

//response array
$response = array();

$response['error'] = false;

$response['message'] = "Musics fetched successfully.";

$response['musics'] = array();

//traversing through all the rows

while($row =mysqli_fetch_array($result)){
    $temp = array();
    $temp['id'] = $row['id'];
    $temp['canzone'] = $row['canzone'];
    $temp['canzone_cantante'] = $row['canzone_cantante'];
    $temp['url'] = $row['url'];
    array_push($response['musics'],$temp);
}

echo json_encode($response);
}

You are sending your canzone parameter with get request( inAndroid) but trying to get it by POST global variable(in php) so i suggest changing your php from $canzone= $_POST['canzone']; to $canzone= $_GET['canzone'];

EDIT also change the if statement here

if($_SERVER['REQUEST_METHOD']=='POST'){

to

if($_SERVER['REQUEST_METHOD']=='GET'){

You send song name as GET not like post.

Also you need to urlencode name of a song, if it has more then one word in name.

Cheers :)

Try with replacing this line

 $canzone = $_POST['canzone'];

with

 $canzone = $_REQUEST['canzone'];

As I understood you post the request like this from Android App

String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;

But there is a problem that you send 'canzone' in URL, so this is GET parameter, and in the PHP you grab this variable from $_POST, just change $_POST to $_GET, should work

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