dongli5785 2016-06-01 23:58
浏览 85

无法使用PHP连接到MySQL - Android Studio

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!

  • 写回答

1条回答

  • dongtong5242 2016-06-02 00:30
    关注

    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...

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决