-3

I have the following script which allows the user from my android app to rate the football players of a team.

<?php
  require "init.php";
  header('Content-type: application/json');

  error_reporting(E_ALL); 
  ini_set("display_errors", 1);

  $id = $_POST['id'];
  $user_id = $_POST['User_Id'];
  $best_player = $_POST['player'];
  $rate = $_POST['rate'];

  if($best_player){

        $sql_query = "insert into ratingplayerstable values('$id','$bestplayer','$rate','$user_id');";

        if(mysqli_query($con,$sql_query)){
            $_SESSION['id'] = mysqli_insert_id($con);
            $don = array('result' =>"success","message"=>"Επιτυχής πρόσθεση παίχτη");
        }       
     }else if($best_player){
        $don = array('result' =>"fail","message"=>"Παρακαλώ συμπλήρωσε τα πεδία");               
    }      
     echo json_encode($don);

?>

When I run it as it is from my server,I get the following the following message:

<br />
<b>Notice</b>:  Undefined index: id in <b>/var/www/vhosts/theo-  
android.co.uk/httpdocs/ael/cms/insert_best_players.php</b> on line <b>7</b>   
<br />
<br />

<b>Notice</b>:  Undefined index: User_Id in <b>/var/www/vhosts/theo-
android.co.uk/httpdocs/ael/cms/insert_best_players.php</b> on line <b>8</b>  
<br />
<br />

<b>Notice</b>:  Undefined index: player in <b>/var/www/vhosts/theo-  
android.co.uk/httpdocs/ael/cms/insert_best_players.php</b> on line <b>9</b>  
<br />
<br />
<b>Notice</b>:  Undefined index: rate in <b>/var/www/vhosts/theo-
android.co.uk/httpdocs/ael/cms/insert_best_players.php</b> on line <b>10</b>  
<br />
<br />
<b>Notice</b>:  Undefined variable: don in <b>/var/www/vhosts/theo- 
android.co.uk/httpdocs/ael/cms/insert_best_players.php</b> on line <b>38</b>   
<br />
null

Without sending any data I should had get

{"fail":"Παρακαλώ συμπλήρωσε τα πεδία"}

Why is this happening? All the values like id,players etc are defined in my table. This is how I created the table:

CREATE TABLE IF NOT EXISTS `ratingplayerstable ` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `player` text NOT NULL,
 `rating` text NOT NULL,
 `User_Id`int(10) NOT NULL,

  PRIMARY KEY (`id`),
  FOREIGN KEY (User_Id) REFERENCES user_info(User_Id)

  ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=30;

Thanks,

Theo.

edit

This is how i do the post request from the Android.

private void ratingPlayer(final String player, final String rating,final String UserId) {
    // Tag used to cancel the request

    //HttpsTrustManager.sssMethod();
    String tag_string_req = "req_register";


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

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

            try {
                JSONObject jsonObject = new JSONObject(response);
                if (jsonObject.getString("result").equals("success")) {

                    Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();


                } else if (jsonObject.getString("result").equals("fail")) {

                    Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error", "Registration Error: " + 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("id", "");
            params.put("User_Id", UserId);
            params.put("player", player);
            params.put("rating", rating);
            return params;
        }
    };
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

 }

login.php

<?php
       session_start();
       require "init.php";
       header('Content-type: application/json');


       $user_name = $_POST['user_name'];
       $user_pass = $_POST['user_pass'];
       $passwordEncrypted = sha1($user_pass);



       if($user_name && $user_pass){

            $sql_query = "select * from user_info where user_name ='".mysqli_real_escape_string($con, $user_name)."' and user_pass='".mysqli_real_escape_string($con, $passwordEncrypted)."' LIMIT 1";      

            $result = mysqli_query($con,$sql_query);

            $row = mysqli_fetch_array($result);



            if($row){


                $don = array('result' =>'success','message'=>'You are logged in');
                $_SESSION['id'] = $row['id'];

            }else{

                $don = array('result' =>'fail','message'=>'User could not be found');
            }
        }else if(!user_name){


            $don = array('result' =>"fail","message"=>"Please enter your name");               


        }else if(!$user_pass){

         $don = array('result' =>"fail","message"=>"Please enter your password");

        }

        echo json_encode($don);

  ?>
Theo
  • 3,099
  • 12
  • 53
  • 94
  • Because when you run it from your server - no one does POST request. – u_mulder Jul 14 '16 at 08:03
  • 2
    Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Epodax Jul 14 '16 at 08:04
  • The error has nothing to do with the definition of your DB table. It means that the data you're looking for in `$_POST` isn't there. Try `var_dump($_POST);` at line 7 and check the contents of `$_POST` – Ben Hillier Jul 14 '16 at 08:04
  • @Ben Hillier. I get array(0) – Theo Jul 14 '16 at 08:06
  • You're not POSTing any data to the script so all the indexes are undefined and since `$best_player` therefore is `null` it's jumping straight to your `json_encode` - which is attempting to encode a variable (`$don`) that is only set inside the `if` condition that's just been skipped. You're also wide open to SQL injection attacks. – CD001 Jul 14 '16 at 08:09
  • @Theo Then `$_POST` is not set. That means that the page/app that calls the script is not sending the data for some reason. I've placed an answer which shows how to suppress the error messages; but the real issue, I suspect, is somewhere else. – Ben Hillier Jul 14 '16 at 08:09
  • Can you provide your submitting form? Probably the root of your issue sits there. – dios231 Jul 14 '16 at 08:23
  • @dios231. The form part is done from the Android part. – Theo Jul 14 '16 at 08:42
  • @dios231. please see edit – Theo Jul 14 '16 at 08:43

4 Answers4

1

This will let you lookup the contents of $_POST without any error messages:

  $id = isset($_POST['id']) ? $_POST['id'] : false;
  $user_id = isset($_POST['User_Id']) ? $_POST['User_Id'] : false;
  $best_player = isset($_POST['player']) ? $_POST['player'] : false;
  $rate = isset($_POST['rate']) ? $_POST['rate'] : false;
Ben Hillier
  • 2,126
  • 1
  • 10
  • 15
0

First Ben Hillier is absolutely right, DO NOT USE global virables like $_POST directly. Second you try to run your script "on fly" without sending any values. For testing purpose try

<?php
  require "init.php";
  header('Content-type: application/json');

  error_reporting(E_ALL); 
  ini_set("display_errors", 1);

  $id = isset($_POST['id'])?$_POST['id']:$_GET['id'];
  $user_id = isset($_POST['User_Id'])?$_POST['User_Id']:$_GET['User_Id'];
  $best_player = isset($_POST['player'])?$_POST['player']:$_GET['player'];
  $rate = isset($_POST['rate'])?$_POST['rate']:$_GET['rate'];

  if($best_player){

        $sql_query = "insert into ratingplayerstable values('$id','$bestplayer','$rate','$user_id');";

        if(mysqli_query($con,$sql_query)){
            $_SESSION['id'] = mysqli_insert_id($con);
            $don = array('result' =>"success","message"=>"Επιτυχής πρόσθεση παίχτη");
        }       
     }else if($best_player){
        $don = array('result' =>"fail","message"=>"Παρακαλώ συμπλήρωσε τα πεδία");               
    }      
     echo json_encode($don);

and try to run it with get method eg script.php?id=1&User_Id=12&player=55&rate=5

I think there is no other problem

0

You should check if POST data was submitted:

if (!empty($_POST))
{
    // do stuff
}
0

The answer of Ben is correct. You should have search that because it's a common error.

Moreover check your code:

if($best_player){
    // ...
} else if($best_player){
    // ...
} 

Write else instead of else if($best_player)

Edit:

Also, use a 'satinize function' because in the post data someone can make a code injection attack.

dimasdmm
  • 318
  • 4
  • 15