将变量从 Android 应用程序发送到 MySQL 数据库时出现问题

问题描述 投票:0回答:1

我想使用 POST 将字符串值从我的应用程序传递到 MySQL localhost 数据库,但是当我调用函数 registerUser() 时,我的数据库没有收到它。这是负责将变量发送到数据库的代码。主要在函数registerUser();.

    private void registerUser(){
        final String username = regUsername.getText().toString().trim();
        final String password = regPass2.getText().toString().trim();
        final String email = regEmail.getText().toString().trim();
        final String phone = regPhone.getText().toString().trim();
        final String type = "student";

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                Constants.URL_REGISTER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Toast.makeText(getApplicationContext(), jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                
                params.put("username", username);
                params.put("password", password);
                params.put("email", email);
                params.put("phone", phone);
                params.put("type", type);
                return  params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }
    

下面是php脚本

Constants.php
?php
    define('DB_NAME','munchub');
    define('DB_USER','root');
    define('DB_PASSWORD','');
    define('DB_HOST','localhost');

?>

DbConnect.php
<?php
    class DbConnect{
        private $con;
        
        function __construct(){
        }
        
        function connect(){
            include_once dirname(__FILE__).'/Constants.php';
            $this->con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
            
            if(mysqli_connect_errno()){
                echo "Failed to connect with database".mysqli_connect_err();

            }

            return $this->con;
        }
    }

?>

DbOperations.php
<?php
    Class DbOperations{

        private $con;
        function __construct(){

            require_once dirname(__FILE__).'/DbConnect.php';
            $db = new DbConnect();
            $this->con = $db->connect();
        }
        
        /*CRUD - > C -> CREATE*/
        
        function createUser($custName, $custPass, $custEmail, $custPhone, $custType){

            $encryptedPassword = md5($custPass);
            $stmt = $this->con->prepare("INSERT INTO `customer` (`Customer_ID`, `Cust_Name`, `cust_pass`, `Cust_Email`, `Cust_Phone`, `Cust_Type`) VALUES (NULL, ?, ?, ?, ?, ?);");
            $stmt->bind_param("sssss",$custName,$encryptedPassword,$custEmail,$custPhone,$custType);

            if($stmt->execute()){
                return true;
            }else{
                return false;
            }
        }
    }

?>

registerUser.php
<?php

require_once '../includes/DbOperations.php';


    $response = array();

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        if(
            isset($_POST['username']) and 
            isset($_POST['password']) and 
            isset($_POST['email']) and 
            isset($_POST['phone']) and 
            isset($_POST['type'])) {

            $db = new DbOperations();
            if($db->createUser(
                $_POST['username'],
                $_POST['password'],
                $_POST['email'],
                $_POST['phone'],
                $_POST['type'])){
                $response['error'] = false;
                $response['message'] = "User registered successfully";
            }else{
                $response['error'] = true;
                $response['message'] = "Error occur";
            }

        }else{
            $response['error'] = true;
            $response['message'] = "Required fields are mising";
        }


    }else{
        $response['error'] = true;
        $response['message'] = "Invalid Request";
    }
    echo json_encode($response);
?>

我已经使用 Postman 应用程序测试了我的 php 脚本,它设法将变量传递到数据库。我已经测试了 Constants.URL_REGISTER 中的地址,它指向 php 文件。

java android android-volley
1个回答
0
投票

我在我的应用程序中发现了该问题。所有代码和php脚本都很好。我需要做的只是在 android 清单中添加这一行

android:usesCleartextTraffic="true"
© www.soinside.com 2019 - 2024. All rights reserved.