无法存储数据JSON

时间:2014-02-24 13:47:35

标签: php android json

我正在尝试创建一个注册和登录功能,但我遇到了JSON问题,因为它无法存储数据。

这是我得到的日志的json响应: 02-24 08:24:47.878: E/JSON(2017): {"tag":"register","success":0,"error":1,"error_msg":"Error occured in Registartion"}

这是我存储数据的PHP代码:

<?php
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];

// include db handler
require_once 'DB_Function.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["user"]["email"] = $user["email"];
        $response["user"]["contact"] = $user["contact_no"];
        $response["user"]["created_at"] = $user["year_joined"];

        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
    $email = $_POST['email'];
    $password = $_POST['password'];
    $contact = $_POST['contact'];

    // 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($email, $contact, $password);
        if ($user) {
            // user stored successfully
            $response["success"] = 1;
            $response["user"]["email"] = $user["email"];
            $response["user"]["contact"] = $user["contact_no"];
            $response["user"]["created_at"] = $user["year_joined"];

            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";
}
?>

登录和注册功能共享用户功能类:

public class UserFunctions {

private JSONParser jsonParser;
private static String loginURL = "http://10.0.2.2:8000/project/index.php";
private static String registerURL = "http://10.0.2.2:8000/project/index.php";

private static String login_tag = "login";
private static String register_tag = "register";

// constructor
public UserFunctions() {
    jsonParser = new JSONParser();
}

// login with user provided email/pass
public JSONObject loginUser(String email, String password) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.makeHttpRequest(loginURL, "GET", params);
    return json;
}

// register a new user 
public JSONObject registerUser(String email, String password, String contact) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    params.add(new BasicNameValuePair("contact", contact));
    //params.add(new BasicNameValuePair("year", Integer.toString(year)));

    // getting JSON Object
    JSONObject json = jsonParser.makeHttpRequest(registerURL, "GET", params);
    return json;
}

// determine if the user is logged in
public boolean isUserLoggedIn(Context context) {
    DatabaseHandler db = new DatabaseHandler(context);
    int count = db.getRowCount();
    if (count > 0) {
        // user logged in
        return true;
    }
    return false;
}

// logout the user
public boolean logoutUser(Context context) {
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}
}

2 个答案:

答案 0 :(得分:0)

可能的麻烦之一可能是您通过GET方法发送参数,但在PHP脚本中,您尝试解析空内容的POST内容。尝试使用jsonParser.makeHttpRequest(registerURL, "POST", params);代替jsonParser.makeHttpRequest(registerURL, "GET", params);

答案 1 :(得分:0)

<?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) {
    $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, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$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 {
        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'");
    $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;
}

}

?>