我正在尝试从工作状态修改一些代码,以添加更多功能来理解代码的工作方式。所以基本上我试图通过为用户提供创建新赌注的选项来添加其他功能。在我修改之前它工作正常,很好,我的意思是用户能够登录并注册任何问题。即使布局也显示没有任何问题。
为了进行比较,我将在版本之前和之后添加相同的php文件。
index.php 之前
<?php
/**
* File to handle all API requests
* Accepts GET and POST
*
* Each request will be identified by TAG
* Response will be JSON data
/**
* check for POST request
*/
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login')
{
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false)
{
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else
{
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
else if ($tag == 'register')
{
// Request type is Register new user
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$prefered_username = $_POST['preffered'];
// check if user is already existed
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = 2;
$response["error_msg"] = "User already existed";
echo json_encode($response);
}
else
{
// store user
$user = $db->storeUser($name, $email, $password, $prefered_username);
if ($user)
{
// user stored successfully
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
}
else
{
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
}
else
{
echo "Invalid Request";
}
}
else
{
echo "Access Denied";
}
?>
index.php
之后 <?php
/**
* File to handle all API requests
* Accepts GET and POST
*
* Each request will be identified by TAG
* Response will be JSON data
/**
* check for POST request
*/
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login')
{
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false)
{
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else
{
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
else if ($tag == 'register')
{
// Request type is Register new user
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$prefered_username = $_POST['preffered'];
// check if user is already existed
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = 2;
$response["error_msg"] = "User already existed";
echo json_encode($response);
}
else
{
// store user
$user = $db->storeUser($name, $email, $password, $prefered_username);
if ($user)
{
// user stored successfully
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
}
else
{
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
}
/********************************************************************************************************************************************************/
else if ($tag == 'betregister')
{
/*
// Request type is New Bet Register
$bet_uid = $_POST['uid'];
$bet_id = $_POST['betid'];
$bet_starttime = $_POST['start_time'];
$bet_updated = $_POST['updated'];
$bet_status = $_POST['bet_status'];
$bet_users = $_POST['bet_users'];
*/
$bet_name = $_POST['bet_name'];
$bet_brief = $_POST['bet_brief'];
$bet_description = $_POST['bet_description'];
$bet_value = $_POST['bet_value'];
$bet_endtime = $_POST['end_time'];
// check if bet already exists
if ($db->betExists($bet_name))
{
// bet already existed - error response
$response["error"] = 2;
$response["error_msg"] = "bet already existed";
echo json_encode($response);
}
else
{
// create bet
$bet = $db->createNewBet($bet_name, $bet_brief, $bet_description, $bet_value,$bet_endtime);
if ($bet)
{
// bet created successfully
$response["success"] = 1;
$response["uid"] = $bet["uid"];
$response["betid"] = $bet["betid"];
$response["bet"]["bet_name"] = $bet["bet_name"];
$response["bet"]["bet_brief"] = $bet["bet_brief"];
$response["bet"]["bet_description"] = $bet["bet_description"];
echo json_encode($response);
}
else
{
// bet failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured in creating new bet";
echo json_encode($response);
}
}
}
else
{
echo "Invalid Request";
}
}
else
{
echo "Access Denied";
}
?>
DBFunctions 之前
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password, $preferred_name) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
echo mysql_error();
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
if(!$result){
return false;
}
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
DBFunctions
之后 <?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password, $preferred_name)
{
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
echo mysql_error();
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
if(!$result){
return false;
}
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
/**
* Check user is betExists or not
*/
public function isbetExists($betName) {
$result = mysql_query("SELECT bet_name from bets WHERE bet_name = '$betName'");
if(!$result){
return false;
}
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// bet exists
return true;
} else {
// bet doesnot exist
return false;
}
}
/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($password)
{
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password)
{
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
/**
* Adding new bet (my new code)
*/
public function createNewBet($betname, $betbrief, $betdescription, $betvalue)
{
$uid = uniqid('',true);
$bet_id = betid('',true);
$result = mysql_query("INSERT INTO bets(bet_name,bet_brief,bet_description) VALUES('$betname','$betbrief','$betdescription')");
}
/*
public function storeUser($name, $email, $password, $preferred_name)
{
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
echo mysql_error();
return false;
}
}*/
}
?>
最后这是我的Android应用程序将使用代码的java类。
package com.techiequickie.james.boadraf;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import databasehandler.DatabaseHandler;
import databasehandler.UserFunctions;
/**
* Created by YP on 17-Nov-14.
*/
public class newBet_activity extends ActionBarActivity
{
EditText inputBetname, inputBetbrief, inputBetdescription;
SeekBar valueSeekbar; //= null;
Button btn_newbet;
// JSON Response node names
private static String KEY_SUCCESS = "success";
@SuppressWarnings("unused")
private static String KEY_ERROR = "error";
@SuppressWarnings("unused")
private static String KEY_ERROR_MSG = "error_msg";
//private static String KEY_UID = "uid";
private static String KEY_BETNAME = "bet_name";
private static String KEY_BETBRIEF = "bet_brief";
private static String KEY_BETDESCRIPTION = "bet_description";
private static String KEY_BETVALUE = "bet_value";
// private static String KEY_CREATED_AT = "created_at";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newbet);
// Importing all assets like buttons, text fields
inputBetname = (EditText) findViewById(R.id.betName_et);
inputBetbrief = (EditText) findViewById(R.id.betBriefDescription_et);
inputBetdescription = (EditText) findViewById(R.id.betDescription_et);
btn_newbet = (Button) findViewById(R.id.bet_btn);
//valueSeekbar = (SeekBar) findViewById(R.id.betValue_bar);
/*
valueSeekbar.setOnSeekBarChangeListener
(
new SeekBar.OnSeekBarChangeListener()
{
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(newBet_activity.this, "seek bar progress:" + progressChanged, Toast.LENGTH_SHORT).show();
}
}
);*/
btn_newbet.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String betname = inputBetname.getText().toString();
String betBrief = inputBetbrief.getText().toString();
String betDescription = inputBetdescription.getText().toString();
//StringBuilder betValue = ((toString()) valueSeekbar.getProgress());
new BetRegisterTask().execute(betname,betBrief,betDescription);
}
}
);
}
class BetRegisterTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... params)
{
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.createBet(params[0], params[1], params[2]);
// check for login response
try
{
if (json.getString(KEY_SUCCESS) != null)
{
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1)
{
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user;
json_user = json.optJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.newBet(json_user.getString(KEY_BETNAME), json_user.getString(KEY_BETBRIEF), json.getString(KEY_BETDESCRIPTION));
return "1";
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
return "0";
}
@Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
if (s.equals("1"))
{
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), Loginactivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
showToastforSucessfulBetCreation();
}
else
{
// Error in registration
//registerErrorMsg.setText("Error occurred in registration");
showToastforUnsucessfulBetCreation();
}
}
}
public void showToastforSucessfulBetCreation() {
Toast toast = Toast.makeText(this, "Registration Sucessfull", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 30);
toast.show();
}
public void showToastforUnsucessfulBetCreation() {
Toast toast = Toast.makeText(this, "Registration UnSucessfull", Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 30);
toast.show();
}
}
但是现在我无法登录应用程序本身,这是我之前能够做到的。
EDIT 添加Dropbox链接超出字符限制 https://www.dropbox.com/s/iszqh2mjw23kyvq/register_java_class.txt?dl=0