无法使用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!

duancuo1234
duancuo1234 在这里或这里阅读准备好的陈述。通常,您忘记绑定值
4 年多之前 回复
dongzhong2008
dongzhong2008 你正在将'标准'sql与准备好的语句混合在一起。准备好的语句是首选方式,但您没有为此提供任何值!
4 年多之前 回复

1个回答



您忘记了 bind </ code>您的值到sql语句。 </ p>

这是一个'应该'工作的代码(我现在没有用android测试它......如果它不起作用,我很乐意改进答案......):

另外请注意,我切换到面向对象的风格。 欲了解更多信息,请阅读手册!</ p> \ n

 &lt;?php 
$ servername =“我的服务器在这里”;
$ username =“我的用户名在这里”;
$ password =“我的密码在这里”;
$ dbname =“我的数据库在这里”;

//创建连接
$ mysqli = new mysqli($ servername,$ username,$ password,$ dbname);
//检查连接
if(!$ mysqli){

//显示错误
}

$ sql =“INSERT INTO用户(用户名,电子邮件,密码)VALUES(?,?,?)”;

nif($ stmt = $ mysqli- &gt;准备($ sql)){
//这是你缺少的:
$ stmt-&gt; bind_param(“sss”,$ _POST ['username'],$ _POST ['email'],$ _POST ['密码']);
$ stmt-&gt; execute();
//你肯定想在这里进行更多(错误)检查
$ last_id = $ mysqli-&gt; insert_id($ conn);

//和这里

//现在将json返回给android。 添加你想要的任何数据(全新的记录fe)
$ return =“{'成功':true,'id':$ last_id}”;
echo $ return;
} else {
// return 任何错误:
$ return =“{'success':false,'errors':[{'DB-Error':'”。$ sql。“”。$ mysqli-&gt;错误。“'}]}” ;
echo $ return;
}

$ mysqli-&gt; close($ conn);
?&gt;
</ code> </ pre>

注意</ strong>您不应该像我现在那样直接从$ _POST传递值,转义它们,验证它们等等...... </ p>
</ div>

展开原文

原文

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

duanpin2009
duanpin2009 现在有什么成功吗? 我是否回答了您的(初始)问题?
4 年多之前 回复
douliang1900
douliang1900 是的,现在的问题是,你的android期望一个json,但是你返回(echo)一个简单的字符串(“new record created ...”)。 我会马上更新我的答案!
4 年多之前 回复
douyue2313
douyue2313 谢谢Jeff,令人惊讶的是,现在php代码似乎还不错? 检查邮递员它没有返回任何错误,它实际上让我回到成功创建的新记录...但是,当尝试通过Android Studio中的应用程序注册用户时,我仍然得到Json错误:org。 json.JSONException:值<!DOCTYPE类型java.lang.String无法转换为JSONObject - 您现在知道什么是错的吗? :(
4 年多之前 回复
du7979
du7979 是的,我犯了一个错误,现在纠正了:接近结束它必须是$ mysqli->错误; 而不是mysqli->错误。 我忘了$!
4 年多之前 回复
duanrong5927
duanrong5927 杰夫,你好! 谢谢您的回答! 它给了我一个不同的错误,我尝试调试自己,但也没有运气:解析错误:语法错误,意外的T_OBJECT_OPERATOR,期待','或';' 在第26行的/home/a8084829/public_html/Register.php中
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐