我的应用程序的一个功能是允许注册用户输入球员的足球队名称并给他打分。当他添加它时,数据应该在服务器中发布。我认为为了做到这一点,我需要一个关系数据库,这是我可能需要你帮助的地方。
让我告诉你我的代码。
寄存器片段是:
public class RegisterFragment extends Fragment {
private SessionManager session;
EditText etEmail, etUsername, etPassword,etConfirmPassword;
String email, userName, userPass,confirmPassword;
Button registerButton;
public RegisterFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_register, container, false);
Toolbar myToolbar = (Toolbar) v.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
setHasOptionsMenu(true);
etEmail = (EditText)v.findViewById(R.id.name);
etUsername = (EditText)v.findViewById(R.id.user_name);
etPassword = (EditText)v.findViewById(R.id.user_pass);
etConfirmPassword = (EditText)v.findViewById(R.id.confirm_pass);
registerButton = (Button)v.findViewById(R.id.registerBtn);
// Session manager
// Session manager
session = new SessionManager(getActivity());
if (session.isLoggedIn()) {
// User ites already logged in. Take him to main activity
Intent intent = new Intent(getActivity(), Welcome.class);
startActivity(intent);
}
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
email = etEmail.getText().toString();
userName = etUsername.getText().toString();
userPass = etPassword.getText().toString();
confirmPassword = etConfirmPassword.getText().toString();
if(userPass.equals(confirmPassword)){
registerUser(email, userName, userPass, confirmPassword);
}else{
Toast.makeText(getActivity(),"Passwords don't match",Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
private void registerUser(final String email, final String userName,
final String password,final String confirmPassword) {
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Request.Method.POST,
Config.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", "Register Response: " + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("result").equals("success")) {
Toast.makeText(getActivity(),jsonObject.getString("message"), Toast.LENGTH_LONG).show();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = settings.edit();
//editor.putString("id","");
editor.putString("email", email);
editor.putString("user_name", userName);
editor.putString("user_pass", password);
editor.putString("confirm_pass", confirmPassword);
}
else if (jsonObject.getString("result").equals("fail")) {
Toast.makeText(getActivity(),jsonObject.getString("message"), Toast.LENGTH_LONG).show();
}
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Registration Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
//params.put("id","");
params.put("email", email);
params.put("user_name", userName);
params.put("user_pass", password);
params.put("confirm_pass", confirmPassword);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
为处理上述请求而调用的php代码是:
<?php
session_start();
require "init.php";
header('Content-type: application/json');
$id = $_POST['id'];
$email = $_POST['email'];
$user_name = $_POST['user_name'];
$user_pass = $_POST['user_pass'];
$passwordEncrypted = sha1($user_pass);
$confirmPass = $_POST['confirm_pass'];
$confPasswordEncrypted = sha1($confirmPass);
$msg = "Congratulations. You are now registered to the most amazing app
ever!";
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$don = array('result' =>"fail","message"=>"Please enter a valid email");
}
if($email && $user_name && $user_pass && $confirmPass && filter_var($email, FILTER_VALIDATE_EMAIL)){
$sql_query = "select * from user_info WHERE email ='".mysqli_real_escape_string($con, $email)."' or user_name
='".mysqli_real_escape_string($con, $user_name)."'";
$result = mysqli_query($con, $sql_query);
$results = mysqli_num_rows($result);
if ($results){
$don = array('result' =>"fail","message"=>"Email or username exists.");
}else{
$sql_query = "insert into user_info values('$id','$email','$user_name','$passwordEncrypted','$confPasswordEncrypted');";
if(mysqli_query($con,$sql_query)){
$_SESSION['id'] = mysqli_insert_id($con);
$don = array('result' =>"success","message"=>"Successfully
registered!Well done");
mail($email,"Well done. You are registered to my sample app!",$msg);
}
}
}else if(!$email){
$don = array('result' =>"fail","message"=>"Please enter a valid email");
}else if(!$user_name){
$don = array('result' =>"fail","message"=>"Please enter your username");
}else if(!$user_pass){
$don = array('result' =>"fail","message"=>"Please enter a password");
}else if(!confirmPass){
$don = array('result' =>"fail","message"=>"Please confirm your password");
}
echo json_encode($don);
?>
到目前为止一切正常。
接下来,我创建了一个表,用于保存用户输入的数据。
CREATE TABLE IF NOT EXISTS `ratingplayerstable ` (
`player_id` int(10) NOT NULL AUTO_INCREMENT,
`player` text NOT NULL,
`rating` text NOT NULL,
`User_Id`int(10) NOT NULL,
PRIMARY KEY (`player_id`),
FOREIGN KEY (User_Id) REFERENCES user_info(id)
)ENGINE = InnoDB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 30;
所以我将ratingplayerstable的User_Id与user_info的id相关联。
user_info table.
------------------------------------------------
| id | NOT NULL AUTO INCREMENT PRIMARY KEY|
------------------------------------------------
|user_name| TEXT |
------------------------------------------------
|user_pass| TEXT |
------------------------------------------------
|conf_pass| TEXT |
------------------------------------------------
| email | TEXT |
------------------------------------------------
我的问题是如何找到User_Id并通过Android部分发布。 这就是我试图将数据发送到评级扮演者的方式。
private void ratingPlayer(final String player, final String rating,final String UserId) {
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Request.Method.POST,
URL.URL_BEST_PLAYERS, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", "Best player response: " + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("result").equals("success")) {
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} else if (jsonObject.getString("result").equals("fail")) {
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register urls
Map<String, String> params = new HashMap<String, String>();
params.put("player_id", "");
params.put("User_Id", UserId);
params.put("player", player);
params.put("rating", rating);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
正如您所看到的,对于评级我向服务器发布了3件事。播放器的名称,评级和表示注册用户ID的UserId。但我不知道如何获取最后一个变量并发布它。
最后这是评级扮演者的代码。
<?php
require "init.php";
header('Content-type: application/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
$id = isset($_POST['player_id']);
$user_id = isset($_POST['user_id']);
$best_player = isset($_POST['player']);
$rate = isset($_POST['rate']);
if($id && $user_id && $best_player && $rate){
$sql_query = "insert into rating_players_table
values('$id','$bestplayer','$rate','$user_id');";
if(mysqli_query($con,$sql_query)){
$_SESSION['user_id'] = mysqli_insert_id($con);
$don = array('result' =>"success","message"=>"Επιτυχής πρόσθεση
παίχτη");
}
}if(!$best_player){
$don = array('result' =>"fail","message"=>"Insert player name");
}else if(!$rate){
$don = array('result' =>"fail","message"=>"Rate player");
}
echo json_encode($don,JSON_UNESCAPED_UNICODE);
?>
的login.php
<?php
session_start();
require "init.php";
header('Content-type: application/json');
$user_name = $_POST['user_name'];
$user_pass = $_POST['user_pass'];
$passwordEncrypted = sha1($user_pass);
if($user_name && $user_pass){
$sql_query = "select * from user_info where user_name ='".mysqli_real_escape_string($con, $user_name)."' and user_pass='".mysqli_real_escape_string($con, $passwordEncrypted)."' LIMIT 1";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
if($row){
$don = array('result' =>'success','message'=>'You are logged in');
$_SESSION['id'] = $row['id'];
}else{
$don = array('result' =>'fail','message'=>'User could not be found');
}
}else if(!user_name){
$don = array('result' =>"fail","message"=>"Please enter your name");
}else if(!$user_pass){
$don = array('result' =>"fail","message"=>"Please enter your password");
}
echo json_encode($don);
?>