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 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能