连接到数据库

时间:2017-03-19 17:03:16

标签: java php android json

我尝试为我正在做的示例应用创建简单的登录和注册页面。我使用Volley库来处理数据库的请求和响应,我使用000webhost.com来托管我的文件和数据库。

我的LoginActivity是,

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText uname =(EditText)findViewById(R.id.ed1);
    final EditText pword =(EditText)findViewById(R.id.ed2);
    Button Login=(Button)findViewById(R.id.b1);
    TextView register=(TextView)findViewById(R.id.regv);


    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i= new Intent(MainActivity.this,RegisterActivity.class);
            startActivity(i);
        }
    });


    Login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String username = uname.getText().toString();
            final String password = pword.getText().toString();

            // Response received from the server
            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) {
                            String name = jsonResponse.getString("username");

                            Intent intent = new Intent(MainActivity.this, Maps.class);
                            //intent.putExtra("username", username);
                            MainActivity.this.startActivity(intent);
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setMessage("Login Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
            RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
            queue.add(loginRequest);
        }
    });


}

}

和LoginRequest活动是,

public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "my_host/loginfile";
private Map<String, String> params;

public LoginRequest(String username, String password, Response.Listener<String> listener) {
    super(Method.POST, LOGIN_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("username", username);
    params.put("password", password);
}

@Override
public Map<String, String> getParams() {
    return params;
}

}

和login.php文件是,

<?php
$con = mysqli_connect("host", "user", "pwd", "db");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);

mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $username,$email, $password);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true;
    $response["username"] = $username;
    $response["email"] = $email;
    $response["password"] = $password;
}

echo json_encode($response);

&GT;

当我尝试运行应用程序并尝试登录请求时,另一方没有响应或错误。我尝试在数据库表中添加记录并尝试通过登录进行验证,但仍然没有响应。请指教,我不熟悉PHP。

2 个答案:

答案 0 :(得分:0)

听起来你没有连接到数据库服务器。你应该仔细检查你对mysqli_connect()的调用。

$con = mysqli_connect("host", "user", "pwd", "db");

确保您要更换&#34;主机&#34;,&#34;用户&#34;,&#34; pwd&#34;和&#34; db&#34;具有实际数据库连接值的字符串。它们不会像上面显示的那样工作。

这是另一种在mysqli_connect()函数中使用变量的方法。

$dbHost = "host";
$dbUser = "username";
$dbPass = "password";
$dbName = "database";
$con = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);

将引号中的值替换为数据库连接值。

答案 1 :(得分:0)

我首先尝试print_r($statement),看看数据库是否甚至首先返回数据。我认为也可能发生的事情是在准备好的声明中,您正在使用*调用记录中的每一列但在mysqli_stmt_bind_result中您只将结果绑定到3个变量,而可能存在比回来更多的变量。我会尝试类似的东西:

     $statement = mysqli_prepare($con, "SELECT username, email, password FROM user WHERE username = ? AND password = ? LIMIT 1");
    //Change username, email, password to whatever the equivalent are in the database if they are different. 
The Limit 1 also limits you to only 1 record that matches that criteria, which should be the case anyway, but prevents it from running through the whole database.
        mysqli_stmt_bind_param($statement, "ss", $username, $password);
        mysqli_stmt_execute($statement);

        mysqli_stmt_store_result($statement);
        mysqli_stmt_bind_result($statement, $username,$email, $password);

P.S。我不知道为什么你需要返回密码,或者如果你只是测试你的数据库,但如果这将是一个实时的生产代码,不要返回用户密码,尤其是不要存储用户数据库中的纯文本密码,学习如何散列和加密用户密码并存储该密码。只是一些额外友好的建议。