Cannot get Login to work on Android - php

I recently worked with a PHP script that is supposed to hash the password on registration from the android app. The password will hash and be added to the database, but it won't let me login now. There are no error codes coming up either. Here is the code from Android:
public LoginRequest( String username, String password, Response.Listener<String> listener) {
super(Request.Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("password", password);
params.put("username", username);
Here is the PHP script I am supposed to use:
<?php
require("./Password.php");
$con = mysqli_connect("host", "user", "password", "database");
$typeusername = $_POST["username"];
$typepassword = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $phone, $username, $password, $email);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (password_verify($typepassword, $password)) {
$response["success"] = true;
$response["name"] = $name;
$response["phone"] = $phone;
$response["username"] = $username;
$response["password"] = $password;
$response["email"] = $email;
}
}
echo json_encode($response);
?>
Update: This is based off of a template for a login PHP file with a few modifications for my needs. This is closer to what the original template looked like:
<?php
require("./Password.php");
$con = mysqli_connect("host", "user", "password", "database");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colPhone, $colUsername, $colPassword, $colEmail);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (password_verify($password, $colPassword)) {
$response["success"] = true;
$response["name"] = $colName;
$response["phone"] = $colPhone;
$response["username"] = $colUsername;
$response["password"] = $colPassword;
$response["email"] = $colEmail;
}
}
echo json_encode($response);
?>
This is supposed to work with a previous database that I had setup for a tutorial series that this template is based on, but it does not work either. With a regular login PHP code, I can login just fine, but I want to be able to use the hashed passwords in my database.

Related

Number of bind variables doesn't match number of fields in prepared statement when changing a password [duplicate]

This question already has an answer here:
INSERT - Number of bind variables doesn't match number of fields in prepared statement
(1 answer)
Closed 1 year ago.
I'm trying to make a change password but the error:
Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't
match number of fields in prepared statement in
/storage/ssd3/222/2815222/public_html/changepassword.php on line 12
<?php
$con = mysqli_connect("localhost", "id2815222_bigbrother", "orwell", "id2815222_orwell");
$studentno = $_POST["studentno"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "UPDATE tbl_users SET password = ? WHERE studentno = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $id, $studentno, $firstname, $middlename, $lastname, $birthday, $section ,$course, $college, $password, $phonenumber, $email);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
}
echo json_encode($response);
?>
Any idea on how I can fix this?
Update query only return true or false it will not return updated data. So change you code like below:
<?php
$con = mysqli_connect("localhost", "id2815222_bigbrother", "orwell", "id2815222_orwell");
$studentno = $_POST["studentno"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "UPDATE tbl_users SET password = ? WHERE studentno = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
$res = mysqli_stmt_execute($statement); // store result in $res
$response = array();
$response["success"] = false;
if($res){ //check whether it is true or false
$response["success"] = true;
}
echo json_encode($response);
?>

Mysqli_prepare not working

Solving this will allow me to solve another issue. Seems to me the statement isn't preparing or executing properly. I'm using a basic HTML form to debug and I know that the values are getting posted properly for username and password.
<?php
$con = mysqli_connect('localhost', 'user', 'password');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump(mysqli_select_db($con,'db'));
$username = $_POST["username"];
$password = $_POST["password"];
var_dump($username,$password);
$statement = mysqli_stmt_prepare($con, "SELECT password FROM user WHERE username = ?");
var_dump($statement);
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colAge, $colPassword);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (strcmp($password,$colPassword)) {
$response["success"] = true;
}
}
echo json_encode($response);
?>
Here is the form if its of any interest:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="LoginSecure.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
And finally the var_dump:
/home/r38w9q46ii75/public_html/LoginSecure.php:7:boolean true
/home/r38w9q46ii75/public_html/LoginSecure.php:12:string 'test2' (length=5)
/home/r38w9q46ii75/public_html/LoginSecure.php:12:string 'test2' (length=5)
/home/r38w9q46ii75/public_html/LoginSecure.php:14:null
{"success":false}
EDIT: CHANGES:
<?php
$con = mysqli_connect('localhost', 'user', 'password');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump(mysqli_select_db($con,'db'));
$username = $_POST["username"];
$password = $_POST["password"];
var_dump($username,$password);
$statement = mysqli_stmt_init($con);
mysqli_stmt_prepare($statement, "SELECT password FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colPassword);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (strcmp($password,$colPassword)==0) {
$response["success"] = true;
}
}
echo json_encode($response);
?>
here
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colAge, $colPassword);
you wanna bind 5 vars to the result, but your query will only return one: 'password'.
As a consequence the fetch will fail and return false here while(mysqli_stmt_fetch($statement)).
To solve that just remove the unneeded vars from your bind_result:
mysqli_stmt_bind_result($statement, $colPassword);
As an alternative you could of course also add the columns user, name, ... to your query.
BUT please don't store plain passwords in your database.
Use password_hash()!
And third:
You have a locical error here:
if (strcmp($password,$colPassword)) {
$response["success"] = true;
}
strcmp will return 0 if both strings are identical, but >0 if the first param is 'bigger' than the second one.
So strcmp('test2', 'test') will return 1 -> you will return success=true!
And vice versa, if the password is correct you will return success=false now.
You need init and do a SELECT * not only password
Test this:
$statement = mysqli_stmt_init($con);
mysqli_stmt_prepare($statement, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colAge, $colPassword);

PHP Get Method, does not Enter If Statement

I am not sure why it does not enter the if statement in the API class to actually execute the method. The goal of this method is to simply return a specific row of data, when entering a specific username (this is a users database that holds users info etc). Any help in the right direction is welcomed. This is fairly new stuff to me. Thanks
This is the Connect Class. It is working 100%
<?php
class DbConnect{
private $con;
function __construct(){
}
function connect(){
include_once dirname(__FILE__).'/Constants.php';
$this->con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect with database".mysqli_connect_err();
}
return $this->con;
}
}
<?php
This class handles all the functions.
EDIT: So after more testing, I believe the error is in this part of the code.
class DbOperations{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
public function getTheSpecificUser($username){
//$username = $_POST['username'];
//$username = $_POST['username'];
$stmt= $this->con-> prepare("SELECT `id`, `username`, `email`,
`phonenumber`, `birthdate`, `lastname`, `firstname`, `middlename`
FROM `users` WHERE `username` = ?");
$stmt->bind_param("s", $username);
$stmt->bind_result( $id, $username, $email, $phonenumber,
$birthdate, $lastname, $firstname, $middlename);
$stmt->execute();
//$stmt->bind_result("isssssss", $id, $username, $email,
//$phonenumber, $birthdate,
//$lastname, $firstname, $middlename);
$results = array();
//$results = $stmt->fetch();
while($stmt->fetch()){
$result = array();
$result['id'] = $id;
//$result['username'] = $username;
$result['email'] = $email;
$result['phonenumber'] = $phonenumber;
$result['birthdate'] = $birthdate;
$result['lastname'] = $lastname;
$result['firstname'] = $firstname;
$result['middlename'] = $middlename;
array_push($results, $result);
}
return $results;
}
This is the class that handles all the operations.
This is where the method is called from DbOpertaions. It is included and works correctly with other functions.
EDIT: I do not think the error is here, because if the statement is taken out of the if statement, then it should fire, but nothing happens if added to $response. So again the error must be in the DbOperaitions class.
<?php
//getting the dboperation class
require_once '../includes/DbOperations.php';
$response = array();
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'getthespecificuser':
if(isset($_GET['username'])){
echo "you are past the frist if statement";
$db = new DbOperations();
if($db->getTheSpecificUser($_GET['username'])){
echo "you are in the second if statement";
$response['error'] = false;
$response['id'] = $user['id'];
$response['username'] = $user['username'];
$response['email'] = $user['email'];
$response['phonenumber'] = $user['phonenumber'];
$response['lastname'] = $user['lastname'];
$response['firstname'] = $user['firstname'];
$response['middlename'] = $user['middlename'];
}else{
echo "-->";
var_dump($_GET['username']);
die();
$response['error'] = true;
$response['message'] = "something went wrong";
}
}else{
$response['error'] = true;
$response['message'] = "please enter a valid username";
}
break;
}else{
//if it is not api call
//pushing appropriate values to response array
$response['error'] = true;
$response['message'] = 'Invalid API Call`enter code here`';
}
//displaying the response in json structure
echo json_encode($response);

Cannot fetch the name,username and password

When I try to login it shows Incorrect user details. Although the data is getting inserted but not getting fetched.
Following are my two PHP files.
Register.php
<?php
$con=mysqli_connect("mysql.hostinger.in","name","password","u721174658_swap");
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO `user` (name,username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name,$username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
FetchUserData.php
<?php
$con=mysqli_connect("mysql.hostinger.in","name","password","u721174658_swap");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM `user` WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name,$username, $password);
$user = array();
while(mysqli_stmt_fetch($statement)){
$user["name"] = $name;
$user["username"] = $username;
$user["password"] = $password;
}
echo json_encode($user);
mysqli_close($con);
?>
use to fetch the following way and session start
while($row= mysql_fetch_array($statement){
$name = $row['name'];
}

php script echoing part of the php instead of what intended [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 2 years ago.
I'm having trouble with php script that I've created to insert instances into a database, however I'm getting a trivial output and i dont know how to fix it. the code is:
<?php
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$password = sha1($_POST['password']);
$location = %_POST['location'];
$email = $_POST['email'];
$name = $_POST['fname'] . " " . $_POST['surname'];
$check = $pdo->prepare('SELECT * FROM user WHERE username=?');
$check->bindValue(1, $username);
$check->execute();
if($check->fetch(PDO::FETCH_OBJ)){
echo "Account name already exists";
}
else{
$stmt = $pdo->prepare('INSERT INTO user(username, password, location, email, name)
VALUES(:username, :password, :location, :email, :name)');
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if($stmt->execute()){
echo "Account created";
}
else{
echo "Account could not be created";
}
}
$pdo = null;
}catch(PDOException $e){
echo $e->getMessage();
}
?>
i would expect the output to be something like "Account created". Instead the output I'm getting this error:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $username =
$_POST['username']; $password = sha1($_POST['password']);
$location = %_POST['location']; $email = $_POST['email']; $name =
$_POST['fname'] . " " . $_POST['surname']; $check =
$pdo->prepare('SELECT * FROM user WHERE username=?');
$check->bindValue(1, $username); $check->execute();
if($check->fetch(PDO::FETCH_OBJ)){ echo "Account name already exists";
} else{ $stmt = $pdo->prepare('INSERT INTO user(username, password,
location, email, name) VALUES(:username, :password, :location, :email,
:name)'); $stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if($stmt->execute()){ echo "Account created"; } else{ echo "Account
could not be created"; } } $pdo = null; }catch(PDOException $e){ echo
$e->getMessage(); } ?>
whats going wrong with this script to cause this?
The only way you'd get that output is if you had written:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
as:
$pdo?>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
by mistake.
YOU HAVE a % INSTEAD OF $ on %_POST['location']
RECOMMENDATION:
Also I HIGHLY recommend wrapping the PDO functions into a class. Here is what I use personally in every single project:
save this to it's own file (ex:sql.class.php)
<?php
class SqlIt{
public $Sql;
public $Response;
private $Host;
private $DBname;
private $User;
private $Pass;
public $NumResults;
public function __construct($Sql, $type, $vars){
if($vars == ""){
$vars = array();
}
try{
$DB = $this->db_connect();
$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DB->prepare($Sql);
$doit = $STH->execute($vars);
$this->Result = $doit;
}
catch(PDOException $e){
echo $e->getMessage();
}
//find function to run
switch($type){
case 'select':
$this->select($STH);
break;
}
}
public function select($query){
$rows = $query->rowCount();
$this->NumResults = $rows;
while($row = $query->fetchObject()){
$this->Response[] = $row;
}
}
//create a separate function for connecting to DB. Private to only this class.
private function db_connect(){
$this->User = 'root';
$this->Pass = '';
$DBH = new PDO("mysql:host=localhost;dbname=divebaby", $this->User, $this->Pass);
return $DBH;
}
}
?>
Then to actually run the statement you placed above you simply right the following code:
$username = $_POST['username'];
$password = sha1($_POST['password']);
$location = $_POST['location'];
$email = $_POST['email'];
$name = $_POST['fname'] . " " . $_POST['surname'];
$getUser = new SqlIt("SELECT * FROM user WHERE username=?","select",array($username));
if($getUser){
echo 'Account name already exists';
}else{
$insertUser = new SqlIt("INSERT INTO user (username,password,location,email,name) VALUES (?,?,?,?,?)","insert",array($username,$password,$location,$email,$name));
if($insertUser){
echo 'Account created!';
}else{
echo 'Account not created.';
}
Missing <?php at the beginning of one of your pages that contains that code with the first line of setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Categories