michael michael - 5 months ago 33
JSON Question

JSON and PHP Error Occurred in registration- Android Studio

When ever I try to register a user, I get the below error and it does not insert the data into my database and table which is on localhost wamp server and the database is saved on myphpadmin, When I register a user I get the below error message which he occurs if user fails to register. I have four PHP files which are index.php where the error is coming from as it does not register the user on my phpadmin database so no data gets entered into the database.

Error Log


07-23 15:23:10.833 2133-2395/com.bradvisor.bradvisor E/JSON﹕ No database selected
07-23 15:23:10.833 2133-2395/com.bradvisor.bradvisor E/JSON Parser﹕ Error parsing data org.json.JSONException: Value No of type
java.lang.String cannot be converted to JSONObject


PHP Files

Index.PHP

<?php

/**
PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
**/

if (isset($_POST['tag']) && $_POST['tag'] != '') {
// Get tag
$tag = $_POST['tag'];

// Include Database 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["user"]["fname"] = $user["firstname"];
$response["user"]["lname"] = $user["lastname"];
$response["user"]["email"] = $user["email"];
$response["user"]["uname"] = $user["username"];
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_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 == 'chgpass'){
$email = $_POST['email'];

$newpassword = $_POST['newpas'];


$hash = $db->hashSSHA($newpassword);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"];
$subject = "Change Password Notification";
$message = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nBradVisor Team.";
$from = "contact@BradVisor.com";
$headers = "From:" . $from;
if ($db->isUserExisted($email)) {

$user = $db->forgotPassword($email, $encrypted_password, $salt);
if ($user) {
$response["success"] = 1;
mail($email,$subject,$message,$headers);
echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


// user is already existed - error response


}
else {

$response["error"] = 2;
$response["error_msg"] = "User not exist";
echo json_encode($response);

}
}
else if ($tag == 'forpass'){
$forgotpassword = $_POST['forgotpassword'];

$randomcode = $db->random_string();


$hash = $db->hashSSHA($randomcode);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"];
$subject = "Password Recovery";
$message = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nBradVisor Team.";
$from = "contact@BradVisor.com";
$headers = "From:" . $from;
if ($db->isUserExisted($forgotpassword)) {

$user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
if ($user) {
$response["success"] = 1;
mail($forgotpassword,$subject,$message,$headers);
echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}


// user is already existed - error response


}
else {

$response["error"] = 2;
$response["error_msg"] = "User not exist";
echo json_encode($response);

}

}
else if ($tag == 'register') {
// Request type is Register new user
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$uname = $_POST['uname'];
$password = $_POST['password'];



// check if user is already existed
// store user
$user = $db->storeUser($fname, $lname, $email, $uname, $password);
if ($user) {
// user stored successfully
$response["success"] = 1;
$response["user"]["fname"] = $user["firstname"];
$response["user"]["lname"] = $user["lastname"];
$response["user"]["email"] = $user["email"];
$response["user"]["uname"] = $user["username"];
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];

echo json_encode($response);
} else {
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "JSON Error occured in Registartion";
echo json_encode($response);

}
} else {
$response["error"] = 3;
$response["error_msg"] = "JSON ERROR";
echo json_encode($response);
}
} else {
echo "BradVisor Login API";
}
?>


DB_Connect.php File

<?php
class DB_Connect {

// constructor
function __construct() {

}

// destructor
function __destruct() {
// $this->close();
}

// Connecting to database
public function connect() {
require_once 'include/config.php';
// connecting to mysql
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// selecting database
mysqli_select_db($con, "DB_DATABASE");

// return database handler
return $con;
}

// Closing database connection
public function close() {
mysqli_close();
}

}

?>


UserFunction.PHP File

<?php

class DB_Functions {

private $db;

//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new DB_Connect();
$this->db = $db->connect();

}

// destructor
function __destruct() {

}


/**
* Random string which is sent by mail to reset password
*/

public function random_string()
{
$character_set_array = array();
$character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
$character_set_array[] = array('count' => 1, 'characters' => '0123456789');
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
return implode('', $temp_array);
}


public function forgotPassword($forgotpassword, $newpassword, $salt){
$result = mysqli_query($this->db, "UPDATE `users` SET `encrypted_password` = '$newpassword',`salt` = '$salt'
WHERE `email` = '$forgotpassword'");

if ($result) {

return true;

}
else
{
return false;
}

}
/**
* Adding new user to mysqli database
* returns user details
*/

public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt

$result = mysqli_query($this->db,"INSERT INTO `users`(`uid`, `unique_id`, `firstname`, `lastname`, `username`, `email`, `encrypted_password`, `salt`, `created_at`) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysqli_insert_id($this->db); // last inserted id
$result = mysqli_query($this->db, "SELECT * FROM users WHERE uid = $uid");
// return user details
return mysqli_fetch_array($result);
} else {
return false;
}
}

/**
* Verifies user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysqli_query($this->db, "SELECT * FROM users WHERE email = '$email'") or die(mysqli_error($this->db));
// check for result
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
$result = mysqli_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 = mysqli_query($this->db, "SELECT email from users WHERE email = '$email'");
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}

/**
* Encrypting 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
* returns hash string
*/
public function checkhashSSHA($salt, $password) {

$hash = base64_encode(sha1($password . $salt, true) . $salt);

return $hash;
}

}

?>

Answer

From question comments:

Column count doesn't match value count at row 1

The error message says it: in your query, you list a number of columns, and you list a different number of values. Remove uid from your columns list (I assume it has AUTO_INCREMENT attribute).

$result = mysqli_query($this->db,"INSERT INTO `users`(`unique_id`, `firstname`, `lastname`, `username`, `email`, `encrypted_password`, `salt`, `created_at`) VALUES('$uuid', '$fname', '$lname', '$uname', '$email', '$encrypted_password', '$salt', NOW())");
Comments