0

After logging in with email and password, the user tries to add space. When I fill out the form, an error message appears like this" <br/><b> Warning<b>: Undefined Array Key"

    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import com.android.volley.AuthFailureError;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;
    import java.util.HashMap;
    import java.util.Map;

    public class owner_addspace extends AppCompatActivity {

        private EditText titleEditText, addressEditText, postcodeEditText, costEditText;
        private CheckBox availableCheckBox;
        private Button submitButton;
       private String email, password;
   
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_owner_addspace);

            // Get user's email and password from previous activity
            Intent intent = getIntent();
            email = intent.getStringExtra("email");
            password = intent.getStringExtra("password");

            titleEditText = findViewById(R.id.editTextSpace);
            addressEditText = findViewById(R.id.editTextAddress);
            postcodeEditText = findViewById(R.id.editTextPostCode);
            costEditText = findViewById(R.id.editTextCost);
            availableCheckBox = findViewById(R.id.checkBoxIsAvailable);
            submitButton = findViewById(R.id.buttonAddSpace);
    
            submitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String title = titleEditText.getText().toString().trim();
                    String address = addressEditText.getText().toString().trim();
                    String postcode = postcodeEditText.getText().toString().trim();
                    String cost = costEditText.getText().toString().trim();
                    boolean isAvailable = availableCheckBox.isChecked();

                    // Validate the input values
                    if (title.isEmpty()) {
                        titleEditText.setError("Title is required");
                        titleEditText.requestFocus();
                          return;
                    }

                    if (address.isEmpty()) {
                        addressEditText.setError("Address is required");
                        addressEditText.requestFocus();
                        return;
                    }

                    if (postcode.isEmpty()) {
                        postcodeEditText.setError("Postcode is required");
                        postcodeEditText.requestFocus();
                        return;
                    }
   
                    if (cost.isEmpty()) {
                         costEditText.setError("Cost per hour is required");
                        costEditText.requestFocus();
                        return;
                    }

  
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_ADD_SPACE, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Show a toast message
                            Toast.makeText(owner_addspace.this, response, Toast.LENGTH_SHORT).show();

                            // Go back to the main activity
                            finish();
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // Show an error message
                            Toast.makeText(owner_addspace.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> params = new HashMap<>();
                            params.put("ps_title", title);
                            params.put("ps_address", address);
                            params.put("postcode", postcode);
                            params.put("cost_per_hour", cost);
                            params.put("is_available", isAvailable ? "Available" : "Not Available");

                            if(email != null) {
                                params.put("email", email);
                            }
                            if(password != null) {
                                params.put("password", password);
                            }
                            return params;
                        }
                    };

                    Volley.newRequestQueue(owner_addspace.this).add(stringRequest);
                }
            });
        }
    }

php code

    <?php
   // Define database connection parameters
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb";

    // Create database connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check for connection errors
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Get the input values from the form
    $ps_title = $_POST['ps_title'];
    $ps_address = $_POST['ps_address'];
    $postcode = $_POST['postcode'];
    $cost_per_hour = $_POST['cost_per_hour'];
    $is_available = isset($_POST['is_available']) ? "Available" : "Not 
    Available";
    $email = $_POST['email'];
    $password = $_POST['password'];

     // Check if the postcode already exists in the postcode table
    $result = $conn->query("SELECT PostcodeID FROM postcode WHERE Postcode = 
    '$postcode'");

    if ($result->num_rows > 0) {
        // The postcode already exists, get the PostcodeID
        $row = $result->fetch_assoc();
        $postcode_id = $row['PostcodeID'];
    } else {
        // The postcode does not exist, add it to the postcode table and get 
    the PostcodeID
        $conn->query("INSERT INTO postcode (Postcode) VALUES 
    ('$postcode')");
        $postcode_id = $conn->insert_id;
    
        // Use the Google Maps API to get the geolocation data of the postcode
        $geocode_url = "https://maps.googleapis.com/maps/api/geocode/json?address=$postcode&key=AIzaSyB0wJammsFsGqsX5X0s97U10oj_s5_jgM8";
        $geocode_data = json_decode(file_get_contents($geocode_url));
    
        if ($geocode_data->status == "OK") {
            $latitude = $geocode_data->results[0]->geometry->location->lat;
            $longitude = $geocode_data->results[0]->geometry->location->lng;
            $conn->query("UPDATE postcode SET Latitude = '$latitude', Longitude = '$longitude' WHERE PostcodeID = '$postcode_id'");
        }
    }

    // Get the H_ID from the households table using the email and password
    $result = $conn->query("SELECT H_ID FROM households WHERE H_Email = 
    '$email' AND H_Password = '$password'");

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $h_id = $row['H_ID'];
    
        // Insert the parking space into the parkingspace table
        $conn->query("INSERT INTO parkingspace (PS_Title, PS_Address, 
    PostcodeID, H_ID, PS_Cost, PS_Status) VALUES ('$ps_title', 
    '$ps_address', '$postcode_id', '$h_id', '$cost_per_hour', 
    '$is_available', '')");
    
        echo "Parking space added successfully!";
    } else {
        echo "Invalid email or password.";
    }

    // Close the database connection
    $conn->close();
    ?>

when user logged, try to add car space. after filling form and click update button error comes like this
Warning:Undefined Array Key

aynber
  • 22,380
  • 8
  • 50
  • 63
  • That error is most likely coming from your PHP code, not your Android code, though it could be a mismatch of the data your Android code is sending and what the PHP code is expecting. – aynber May 05 '23 at 14:38
  • Now I have added the php code. Please check it out – Hasini Thilakarathna May 05 '23 at 14:45
  • What is the exact error message you're getting? – aynber May 05 '23 at 14:46
  • Warning: Undefined Array Key" – Hasini Thilakarathna May 05 '23 at 14:47
  • There's more to it, specifically which array key is undefined. If it's not there, check your server error logs – aynber May 05 '23 at 14:48
  • when click button 15:56:27.559 D tagSocket(74) with statsTag=0x85bc11fc, statsUid=-1 15:56:28.049 D Compat change id reported: 147798919; UID 10159; state: ENABLED 15:56:28.840 D onActivityFinishing(): calling cancelLocked() – Hasini Thilakarathna May 05 '23 at 14:57
  • Sorry, I meant the web server for the PHP log – aynber May 05 '23 at 15:09
  • i am using android studio with php to connect mysql – Hasini Thilakarathna May 05 '23 at 15:26
  • Yes, and the PHP lives in a webserver, not on the android. You have 2 moving parts in separate areas. – aynber May 05 '23 at 15:32
  • Sorry I dont how to do that. i am new to android and php – Hasini Thilakarathna May 05 '23 at 15:49
  • I would guess Toast.LENGTH_SHORT is truncatating the error messages. Try letting it display the whole message for you. It should tell you _which_ array key is undefined. From just glancing the code, I can see that in the Android code, sending the email and password are optional, but the PHP code is expecting them to always be there. You should check for them using `if (isset($_POST["email]"))` (for example) before trying to use those values. – ADyson May 05 '23 at 17:19
  • P.S. **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unparameterised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson May 05 '23 at 17:19
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use that resource again. – ADyson May 05 '23 at 17:20
  • after debug, i got this error
    Warning: Undefined array key "password" in C:\xampp\htdocs\car\addspace.php on line 24
    Invalid email or password. I tried to register a parking space for a person after successfully logging. After logging, his email and password need to be transferred to the next activity. Can any of you correct the error here?
    – Hasini Thilakarathna May 06 '23 at 15:12
  • As I said previously, I can see that in the Android code, sending the email and password are optional, but the PHP code is expecting them to always be there. You should check for them using if (isset($_POST["email]")) (for example) before trying to use those values – ADyson May 06 '23 at 17:54

0 Answers0