php - 无法向数据库发送和检索数据(PHP/MySQL/Android)

标签 php android mysql

我一直在研究这个PHP-MySQL-Android登录系统,在调试了一些代码问题后,似乎我得到了成功与数据库通信的PHP代码。我通过 PostMan 确认了这一点,我可以在其中输入数据并检索它(运行注册和登录 php 文件)。

但是,从 Android Studio 中的应用程序运行我无法做到这一点。它不会给我代码错误,并且运行良好,但由于某种原因,数据仍然不会进入数据库。如果我手动向其中插入数据,然后尝试使用该应用程序登录,则效果不会很好。我可能在这里遗漏了一些我自己无法看到的基本内容。谁能帮助我在哪里以及如何查看它,看看可能出了什么问题?再次,使用 PostMan,我可以使用当前的 php 文件进行注册和登录,这是否意味着我的问题 100% 出在 Android Studio 中的 Java 代码中?

谢谢大家!

这是我的 RegisterActivity 和 RegisterRequest:

public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "my url is here";
private Map<String, String> params;

public RegisterRequest(String username, String email, String passcode, Response.Listener<String> listener) {
    super(Method.POST, REGISTER_REQUEST_URL, listener, null);
    params = new HashMap<>();

    params.put("username", username);
    params.put("email", email);
    params.put("passcode", passcode);
}

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


public class RegisterActivity extends AppCompatActivity {

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


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

    bRegister.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();
                        System.out.println("OMG");
                    }
                }
            };

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

这是我的 LoginRequest 和 LoginActivity:

public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "my url is here";
private Map<String, String> params;

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

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


public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    final EditText etUsername = (EditText) findViewById(R.id.etUsername);
    final EditText etPassword = (EditText) findViewById(R.id.etPassword);
    final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
    final Button bLogin = (Button) findViewById(R.id.bSignIn);

    tvRegisterLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
            LoginActivity.this.startActivity(registerIntent);
        }
    });

    assert bLogin != null;
    bLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String username = etUsername.getText().toString();
            final String passcode = etPassword.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 username = jsonResponse.getString("username");
                            String email = jsonResponse.getString("email");

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

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

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

这是我的 Register.php:

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO User (username, email, passcode) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $passcode);

$username = $_POST["username"];
$email = $_POST["email"];
$passcode = $_POST["passcode"];

$stmt->execute();

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

echo json_encode($response);

$stmt->close();
$conn->close();   



?>

这是我的 Login.php:

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("SELECT * FROM User WHERE username = ? AND passcode = ?");
    $stmt->bind_param("ss", $username, $passcode);

$stmt->execute(); 

mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $userID, $username, $email, $passcode);


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

while(mysqli_stmt_fetch($stmt)){
    $response["success"] = true;  

    $response["username"] = $username;
    $response["passcode"] = $passcode;
}


echo json_encode($response);

$stmt->close();
$conn->close();


?>

最佳答案

你知道吗...我在 Genymotion 中尝试过(我使用 AS 默认模拟器运行它)并且它有效!

现在,我不知道为什么它没有在默认模拟器上......

关于php - 无法向数据库发送和检索数据(PHP/MySQL/Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37662470/

相关文章:

php - 在 Windows 上使用套接字/路径将 MySQL Workbench 连接到 MAMP

php - 如何为 Laravel 设置文件权限?

php - 我如何指示 artisan 将模型保存到特定目录?

android - 从 ListView 获取检查项目时,获取 SparseBooleanArray.size() 总是 0

android - ScrollView 与 ListView 性能对比

使用文件排序和临时的 MySQL 查询

php - 来自 MYSQL 数据库的结果和查询未以 HTML 格式显示

php - Laravel:区别 App::bind 和 App::singleton

java - 如何制作在 Lollipop 设备上设计的 PreferenceActivity Material ?

sql - 新手的 MySQL 查询优化和 EXPLAIN