php - Android 单选按钮值无法存储在 php mysql : "Required Fields are Missing" 中

标签 php android mysql android-studio xampp

所以我在 Android studio 中创建了几个 editText 字段,每个字段都通过 php 连接到 mysql(我正在使用 xampp 顺便说一句)。现在我的问题是,**在将 tbuyer 从 editText View 更改为 2 RadioButton 即(r_tb; r_ntb)后,它返回“必填字段丢失”**x在 RadioGroup 内。

现在,为了从这两个字符串中获取字符串,我使用 RadioGroup 声明了一个带有条件的 String role="";:

if (radioGroup.getCheckedRadioButtonId() == r_tb.getId())
        {
            role = "Trade Buyer";
        }
        else if (radioGroup.getCheckedRadioButtonId() == r_ntb.getId())
        {
            role = "Non Trade Buyer";
        }

然后将其与将发送到 HashMap 的参数一起传递:

@Override
            protected Map<String, String> getParams() throws AuthFailureError { //put all parameters that will be sent to hash map
                Map<String, String> params = new HashMap<>();
                params.put("cname", cname); //String is converted to final, because we'are using it in a class; refer to line 48-50
                params.put("date", date);
                params.put("lname", lname);
                params.put("fname", fname);
                params.put("mi", mi);
                params.put("email", email);
                params.put("city", city);
                params.put("country", country);
                params.put("tbuyer", role); // check code; String created from radio button

                return params;
            }

然后调用json的字符串请求,这样我们就可以知道注册是否成功。但正如我所说,它返回 **必填字段丢失”

这些是我的Buyer_Registration_Activity.java代码:

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.smdojt.manilafame.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Buyer_Registration_Activity extends AppCompatActivity implements View.OnClickListener{

    private EditText editTextCompanyName, editTextDate, editTextLastName, editTextFirstName, editTextMiddleInitial
            , editTextCity, editTextCountry, editTextType, editTextEmail;
    private Button buttonRegister;
    private ProgressDialog progressDialog;
    String role = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyer_registration);
        //this.setTitle("Buyer Registration");

        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);

        editTextCompanyName = (EditText) findViewById(R.id.editTextCompanyName);
        editTextDate = (EditText) findViewById(R.id.editTextDate);
        editTextLastName = (EditText) findViewById(R.id.editTextLastName);
        editTextFirstName = (EditText) findViewById(R.id.editTextFirstName);
        editTextMiddleInitial = (EditText) findViewById(R.id.editTextMiddleInitial);
        editTextCity = (EditText) findViewById(R.id.editTextCity);
        editTextType = (EditText) findViewById(R.id.editTextType);
        editTextCountry = (EditText) findViewById(R.id.editTextCountry);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);

        buttonRegister = (Button) findViewById(R.id.buttonRegister);
        progressDialog = new ProgressDialog(this);
        buttonRegister.setOnClickListener(this);

    }

    private void registerUser(){
        final String cname = editTextCompanyName.getText().toString().trim();
        final String date = editTextDate.getText().toString().trim();
        final String lname = editTextLastName.getText().toString().trim();
        final String fname = editTextFirstName.getText().toString().trim();
        final String mi = editTextMiddleInitial.getText().toString().trim();
        final String email = editTextEmail.getText().toString().trim();
        final String city = editTextCity.getText().toString().trim();
        final String country = editTextCountry.getText().toString().trim();
        final String tbuyer = editTextType.getText().toString().trim();
        final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        final RadioButton r_tb = (RadioButton) findViewById(R.id.radio_tb);
        final RadioButton r_ntb = (RadioButton) findViewById(R.id.radio_ntb);

        if (radioGroup.getCheckedRadioButtonId() == r_tb.getId())
        {
            role = "Trade Buyer";
        }
        else if (radioGroup.getCheckedRadioButtonId() == r_ntb.getId())
        {
            role = "Non Trade Buyer";
        }
        progressDialog.setMessage("Registering User...");
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                com.example.smdojt.manilafame.sql_demo_2.Constants.URL_REGISTER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {//If there are no ERROR this method will be executed
                        progressDialog.dismiss();
                        //we will get the json object
                        try {
                            JSONObject jsonObject = new JSONObject(response);  //create json object
                            Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error) { // Else, this method will be executed
                        progressDialog.hide();
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError { //put all parameters that will be sent to hash map
                Map<String, String> params = new HashMap<>();
                params.put("cname", cname); //String is converted to final, because we'are using it in a class; refer to line 48-50
                params.put("date", date);
                params.put("lname", lname);
                params.put("fname", fname);
                params.put("mi", mi);
                params.put("email", email);
                params.put("city", city);
                params.put("country", country);
                params.put("tbuyer", role); // check code; String created from radio button
                //params.put("tbuyer", tbuyer);
                return params;
            }
        };

        //add stringRequest (Line 55)
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View view) {
        if (view==buttonRegister)
        {
            registerUser();
        }
    }
}

这些是我的DBOperations.php代码(Crud操作声明)

<?php
//manage all php and db operations

    class DbOperations
    {
        private $con;

        function __construct()
        {
            require_once dirname(__FILE__).'/DbConnect.php'; //import dbconnect to dboperations

            $db = new DbConnect(); //create db connect object

            $this->con = $db->connect();
        }

        //CRUD Operations below
        //Create-----------------------------------------------------------------------------------------------

        function registerBuyer($cname, $date, $lname, $fname, $mi, $email, $country, $city, $tbuyer)
        {
        //$password = md5($password); //encrypt password
        $stmt = $this->con->prepare("INSERT INTO `mfmis_buyers`.`buyers` (`id`, `cname`, `date`, `lname`, `fname`, `mi`, `email`, `country`, `city`, `tbuyer`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); //statement

        //find actual parameters /bind param

        $stmt->bind_param("sssssssss", $cname, $date, $lname, $fname, $mi, $email, $country, $city, $tbuyer); //bind to query

        //execute query below
        if ($stmt->execute()) //as soon as this line is called, data will be inserted into DB
        {
            return true;
        }
        else 
        {
            return false;
        }
        }

        //-----------------------------------------------------------------------------------------------------
    }
?>

这些是我的 registerBuyer.php 代码(其中我的所有错误语句都来自包括“所需字段缺失”)

<?php

require_once '../includes/DbOperations.php';
$response = array();

if($_SERVER['REQUEST_METHOD']=='POST')
{
    if(
        isset($_POST['cname']) and
        isset($_POST['date']) and
        isset($_POST['lname']) and
        isset($_POST['fname']) and
        isset($_POST['mi']) and
        isset($_POST['email']) and
        isset($_POST['country']) and
        isset($_POST['city']) and
        isset($_POST['tbuyer']))
        {
        //operate the data further

        $db = new DbOperations();

        if($db->registerBuyer(
            $_POST['cname'],
            $_POST['date'],
            $_POST['lname'],
            $_POST['fname'],
            $_POST['mi'],
            $_POST['email'],
            $_POST['country'],
            $_POST['city'],
            $_POST['tbuyer']
            ))
        {
            $response['error'] = false;
            $response['message'] = "Buyer Registered Successfully";
        }
        else
        {
            $response['error'] = true;
            $response['message'] = "Some error occured try again";
        }

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

echo json_encode($response);

?>

最佳答案

因此,基于 role 字符串,它甚至不会推送单个数据,因为首先的连接甚至不正确。

所以我上面提到的代码正在工作,唯一妨碍的是我的Constants.java。确保您的本地或在线连接已设置并与 xampp 服务器保持一致。

public class Constants {

    public static final String ROOT_URL = "http://192.168.15.186/MFMIS/register/";

    public static final String URL_REGISTER = ROOT_URL+"registerBuyer.php";
}

确保您的String ROOT_URLURL_REGISTER或任何其他本地和在线连接正确。否则,如果问题仍然存在,则说明您的 Activity 或 xampp 端出现问题。

关于php - Android 单选按钮值无法存储在 php mysql : "Required Fields are Missing" 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42944378/

相关文章:

java - 如果 Fragment 可见,则从 Service 或 BroadcastReceiver 更新 Fragment UI

android - PopupWindow 在某些设备中位于状态栏上方

mysql,如何在特定查询的给定 ID 之前找到插入行的最后一个 id

java - 使用Datanucleus JDO的Servlet找不到MySQL驱动程序

php - 检查时间戳是否是今天

php - 条件语句 - Php Mysqli

PHP:如何对数组的数组执行 htmlspecialchar()?

android - 使用Sencha CMD 6.5 生成的App Android 的CORS 发出POST 请求(403 Forbidden)

mysql - SQL - 为员工建模角色

php - 如何在 if 语句中使用 mysql 别名列