php - 单选按钮的值无法存储到 String 中并保存在 mysql 中

标签 php android mysql radio-button radio-group

在我的应用程序中,注册时,用户可以使用单选按钮(RadioGroup)选择学生或商店所有者的角色

选择并填写注册表后,包括角色在内的所有数据都应存储到mysql中。

不幸的是,只有 nameemailusernamepassword 成功存储,但 role 无法存储。

这是我的 java 文件:

package com.androidhive.dashboard;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import androidhive.dashboard.R;

public class Register extends Activity {

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
RadioGroup rgroup;
Button button3;
int success = 0;
String role = "";

private static String url_register_user = "http://192.168.1.5/database/add_user.php";
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register_layout);

    inputName = (EditText) findViewById(R.id.nameTextBox);
    inputUsername = (EditText) findViewById(R.id.usernameTextBox);
    inputEmail = (EditText) findViewById(R.id.emailTextBox);
    inputPassword = (EditText) findViewById(R.id.passwordTextBox);

    Button button3 = (Button) findViewById(R.id.regSubmitButton);

    final RadioGroup rgroup = (RadioGroup)findViewById(R.id.roleRgroup);
    final RadioButton student = (RadioButton)findViewById(R.id.studButton);
    final RadioButton shopowner = (RadioButton)findViewById(R.id.shopownerButton);

    button3.setOnClickListener(new View.OnClickListener() {         
        public void onClick(View view) {

            String name = inputName.getText().toString();
            String username = inputUsername.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (rgroup.getCheckedRadioButtonId() == student.getId())
            {
                 role = "Student";
            }

            else if(rgroup.getCheckedRadioButtonId() == shopowner.getId())
            {
                 role = "ShopOwner";
            }

            if (name.contentEquals("")||username.contentEquals("")||email.contentEquals("")||password.contentEquals(""))
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);

                builder.setMessage(R.string.nullAlert)
                   .setTitle(R.string.alertTitle);

                builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {

                   }
               });

                AlertDialog dialog = builder.show();
            }
            else
            {
                new RegisterNewUser().execute();
            }           
        }
    });
}

   class RegisterNewUser extends AsyncTask<String, String, String>{
   protected String doInBackground(String... args) {
       String name = inputName.getText().toString();
       String username = inputUsername.getText().toString();
       String email = inputEmail.getText().toString();
       String password = inputPassword.getText().toString();

       List<NameValuePair> params = new ArrayList<NameValuePair>();
       params.add(new BasicNameValuePair("name", name));
       params.add(new BasicNameValuePair("username", username));
       params.add(new BasicNameValuePair("email", email));
       params.add(new BasicNameValuePair("password", password));
       params.add(new BasicNameValuePair("role", role));

       JSONObject json = jsonParser.makeHttpRequest(url_register_user,
                           "GET", params);

       Log.d("Send Notification", json.toString());

       try
           {
                   int success = json.getInt(TAG_SUCCESS);

                   if (success == 1)
                   {

                       if   (role.contentEquals("Student"))
                        {
                            Intent i = new Intent(getApplicationContext(), StudMain.class);
                            startActivity(i);
                            finish();
                        }
                        else if ((role.contentEquals("Shop Owner")))
                        {
                            Intent i = new Intent(getApplicationContext(), ShopMain.class);
                            startActivity(i);
                            finish();
                        }
                        else
                        {
                            AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);

                            builder.setMessage(R.string.roleNullAlert)
                               .setTitle(R.string.alertTitle);

                            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                               public void onClick(DialogInterface dialog, int id) {

                               }
                           });

                            AlertDialog dialog = builder.show();
                        }

                   }

                   else
                   {

                   }
           }

            catch (Exception e)
            {
                  e.printStackTrace();
            }
            return null;
           }
   }
}

和 php 文件:

<?php

// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for required fields
if (isset($_GET['name']) && isset($_GET['username']) && isset($_GET['email']) && isset($_GET['password']) && isset($_GET['role'])) {

$name = $_GET['name'];
$username = $_GET['username'];
$email = $_GET['email'];
$password = $_GET['password'];
$role = $_GET['role'];

// mysql inserting a new row
$result = mysql_query("INSERT INTO register(name, username, email, password) VALUES('$name', '$username', '$email', '$password', '$role')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "You are successfully registered to MEMS.";

    // echoing JSON response
    echo json_encode($response);
} 
else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

除了这两个文件之外,还有什么可能的因素会影响RadioGroup的功能呢?

感谢您的回答.. =)

最佳答案

您的 mysql 插入查询缺少“角色”,这就是您无法保存它的原因。

$result = mysql_query("INSERT INTO register(name, username, email, password) VALUES('$name', '$username', '$email', '$password', '$role')");

更改为

$result = mysql_query("INSERT INTO register(name, username, email, password,role) VALUES('$name', '$username', '$email', '$password', '$role')");

关于php - 单选按钮的值无法存储到 String 中并保存在 mysql 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13658452/

相关文章:

PHP-MySQL : Create variable for undefined index

php - 如何检查变量中的前三个字符?

java - 在 'retrofit2.Retrofit' 中不公开,不能从外部访问

android - 启动特定 PreferenceScreen 的 Intent

mysqldump : Got error: 1045: Access denied for user (using password: YES) when trying to connect server

php - SQL 注入(inject) PDO 保护

php - 从SQL中的文本字段中提取单词

java - 通过 Play 服务 API 将 .txt 文件导出到 Google 云端硬盘时遇到问题

MySql复制一行并替换副本中的部分字段

php - 记录未显示在 MySQL 中,但我可以在 PHP 中通过 ID 获取它