0

I am having some difficulties trying to set up a connection to my database with php... I have tried so many things, double-checked my SQL queries, and just don't see why it is not working... I'm still a newbie, so I guess I'm missing something out of my range yet. I am trying to create an app that will take user registration.

This is the error I'm getting in Android Studio:

org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

My php code is:

<?php
$servername = "my server here";
$username = "my username here";
$password = "my password here";
$dbname = "my db here";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO User (username, email, passcode) VALUES (?, ?, ?)";

if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Another important point, checking in the Postman plugin and verifying the url I get this:

Error: INSERT INTO User (username, email, passcode) VALUES (?, ?, ?)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?)' at line 1

I don't really understand why that is an error? Since I am expecting input from the user in the form...

As in of more information, this is the code from my RegisterActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etUsername = (EditText)findViewById(R.id.etUsername);
    final EditText etEmail = (EditText)findViewById(R.id.etEmail);
    final EditText etPassword = (EditText)findViewById(R.id.etPassword);
    final Button btnRegister = (Button)findViewById(R.id.btnRegister);

    if (btnRegister != null) {
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String username = etUsername.getText().toString();
                final String email = etEmail.getText().toString();
                final String passcode = etPassword.getText().toString();

                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");
                            if (success) {
                                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                RegisterActivity.this.startActivity(intent);
                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry", null)
                                        .create()
                                        .show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                RegisterRequest registerRequest = new RegisterRequest(username, email, passcode, responseListener);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(registerRequest);

So, does anyone know where's this coming from and where else should I look into?

Cheers!

2
  • 1
    you're mixing 'standard' sql with prepared statements. prepared statements is the preferred way, but you didn't provide any values for that! Commented Jun 2, 2016 at 0:06
  • read about prepared statements here or here. Generally, you forgot to bind values Commented Jun 2, 2016 at 0:09

1 Answer 1

1

You forgot to bind your values to the sql-statement.

Here's a code that 'should' work (I didn't test it now with android...and I'm happy to improve the answer if it doesnt work...):
Also note, that I switched to object oriented style. For more information please read the manual!

<?php
$servername = "my server here";
$username = "my username here";
$password = "my password here";
$dbname = "my db here";

// Create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$mysqli) {
    // display error
}

$sql = "INSERT INTO User (username, email, passcode) VALUES (?, ?, ?)";


if ($stmt=$mysqli->prepare($sql)) {
   // HERE's what you're missing:
   $stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['passcode']);
   $stmt->execute();
   // you defenitely want some more (error-)checks here
   $last_id = $mysqli->insert_id($conn);
   // and here

   // now return a json back to android. add any data you want (the whole new record f.e.)
   $return = "{'success':true, 'id': $last_id}";
   echo $return;
} else {
   // return any errors:
   $return = "{'success':false, 'errors': [{'DB-Error': '".$sql." ".$mysqli->error."'}]}";
   echo $return;
}

$mysqli->close($conn);
?>

NOTE You should not pass values from $_POST directly as I did now, escape them, validate them, etc...

Sign up to request clarification or add additional context in comments.

5 Comments

Hi Jeff! Thank you for your answer! It is giving me a different error though, I tried to debug myself, but no luck as well: Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ';' in /home/a8084829/public_html/Register.php on line 26
yes, I made a misstake, now corrected: close to the end it has to be $mysqli->error; instead of mysqli->error. I forgot the $!
Thanks Jeff, surprisingly, now the php code seems to be ok-ish? Checking on Postman it is not returning any errors, and it actually gets me back the New record created succesfully... However, when trying to register an user through the App in Android Studio, I'm still getting the Json error: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject - Do you have any idea what's wrong now? :(
Yeah, the problem now is, that your android expects a json, but you return (echo) a simple string ("New record created..."). I'll update my answer accordingly in a moment!
any success on this now? Did I answer your (initial) question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.