This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
hi i've been using php for a while now but i'm still quiet new to a few things one of which is the bind_result(). So i'm creating a login system on a project but i keep getting the error:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
i know this is to do with the fact that i'm selecting all the columns, what i want to know do i have to bind all of the columns or is their an easier way?
my code in function.php
public function getUserByEmailAndPassword($email, $password) {
$sql = "SELECT * FROM users WHERE email = ?"; // SQL Statement
$stmt = $this->conn->prepare($sql); // Prepare the SQL Statement
$stmt->bind_param('s', $email); // Bind the placeholder with the correct data type from the SQL Statement
$stmt->execute(); // Execute the prepared statement
$stmt->store_result(); // Store the prepared statement for later checking
// Check to make sure if any data is returned
if($stmt->num_rows) {
// Create and append variables
$user = $stmt->bind_result($email);
// Create a while loop
while($stmt->fetch()) {
// verifying user password
$salt = $user['salt'];
$encrypted_password = $user['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
$stmt->close();
return $user;
}else {
}
}
return NULL;
}
}
You can try this code. But as your query is not clear please encrypt your password and then check in if condition
function getUserByEmailAndPassword($email) {
$stmt = $conn->prepare('SELECT
email,
password
FROM users
WHERE email = ?
');
$stmt->bind_param('s',$email);
$stmt->execute();
$stmt->store_result();
while($stmt->fetch()){
$row = array('email'=>$email,'password'=>$password);
}
$stmt->close();
if(!empty($row)){
return $row;
} else {
return "";
}
}
$userDetails = getUserByEmailAndPassword($email);
//Encrypt your password here
if($userDetails['password'] == $encryped_password){
//do_something
}
Related
I have a bad issue on our website and require a solution.
So basically, in the code below, we take the user's email as set it as a username in the database and along with it a random password taken from the MOCK_DATA.csv file and stores it in the database.
But it performs a check, so if the username doesn't already exist in the database, then it inserts the username and password. If the username already exists, then just update the password.
Now here is the issue below:
Description of the issue:
After a user has made a purchase, if the username already exists in the database, the password for that user and all other users in the database are updated to that password.
To clarify, it doesn't happen if it's a new user. So if email abc#gmail.com is not in the database, abc#gmail.com and the password 123456 are inserted into the database and none of the other users in the database have their password affected.
However, if I make a purchase with the same email abc#gmail.com again, the password will be updated for that user (let's say 654321), but all other user's passwords in the database will be set to 654321 as well.
Expected result:
The password should only update for that one single user if the username already exists.
Actual Result:
The password updates for all users.
$email_address = $_GET['email'];
$email_address_metis = "xxx#xxx.com.test-google-a.com";
// Get the access code
$csv = array_map('str_getcsv', file('MOCK_DATA.csv'));
// Get random index from array $arrX
$randIndex = array_rand($csv[0]);
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
//if($_SERVER["REQUEST_METHOD"] == "POST"){
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $email_address; //trim($_POST["username"]);
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
/* store result */
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) == 1) {
$username_err = "exists";
}
} else {
$username = $email_address; //trim($_POST["username"]);
}
} else {
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
//}
// Output the value for the random index
// Validate password
$password = $csv[0][$randIndex];
if ($username_err !== "exists") {
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if ($stmt = mysqli_prepare($link, $sql)) {
// Set parameters
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
// Redirect to login page
// header("location: login.php");
} else {
// echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
} else {
// Prepare an update statement
$sql = "UPDATE users SET password = ? WHERE username = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "si", $param_password, $param_username);
// Set parameters
$param_password = password_hash($password, PASSWORD_DEFAULT);
$param_username = $username;
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
// Password updated successfully. Destroy the session, and redirect to login page
session_destroy();
header("location: login.php");
exit();
} else {
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
So after a long discussion in chat between the OP and I, have come to the conclusion that the $username variable wasn't being populated, which in turn made your query/UPDATE fail because of it, and silently I might add.
Plus, the i in the mysqli_stmt_bind_param() for the UPDATE query was also an issue from the beginning, since you were trying to store a string using an integer format.
I want the following code to return the userID from mysql tblUser of the user if the email and password matched. Currently it is not returning anything
<?php
include 'config.inc.php';
// Check whether username or password is set from android
if(isset($_POST['email']) && isset($_POST['password']))
{
// Innitialize Variable
$result='';
$email = $_POST['email'];
$password = $_POST['password'];
// Query database for row exist or not
$sql = 'SELECT UserID FROM tblUser WHERE email = :email AND password = :password';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount())
{
$result="true" . UserID;
}
elseif(!$stmt->rowCount())
{
$result="false";
}
// send result back to android
echo $result;
}
?>
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.
instead, you could do
if($data = $stmt->fetch())
{
$result="true".$data['UserID'];
}
else
{
$result="false";
}
I have a problem with PHP function password_verify. I've written simple PHP function that uses _GET, takes 3 parameters: $user_unique_id, old_password and new_password. It verifies if old password and the password stored in database are the same. I use hash from my database and compare it with old password using password_verify() fucntion but it returns false even whem I'm 100% sure the passwords are the same. Can somebodyb help me with this problem? I've checked MySQL queries and all works very well. I return updated_at time which later I encode to JSON.
This is my function in main script changeuserpassword.php I call from link:
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// JSON Response Array
$response = array();
// Receiving The Post Params
$old_password = $_GET['old_password'];
$new_password = $_GET['new_password'];
$user_unique_id = $_GET['user_unique_id'];
// Change User Password
$user = $db->changeUserPassword($user_unique_id, $old_password, $new_password);
if ($user != false) {
$response["error"] = false;
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
$response["error"] = true;
$response["error_msg"] = "Podano nieprawidłowe stare hasło";
echo json_encode($response);
}
?>
This is the function I use in changeuserpassword.php main script. It is called changeUserPassword:
/**
* Change User Account Password
*/
public function changeUserPassword($user_unique_id, $old_password, $new_password) {
$stmt = $this->conn->prepare("SELECT user.`encrypted_password`
FROM `user`
WHERE user.`unique_id` = ?"); // Preparing SELECT Query To The `user` Table
$stmt->bind_param("s", $user_unique_id); // Binding With Params
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc(); // Fetching Rows From Query
$stmt->close();
$password_hash = $user["encrypted_password"]; // Decrypting Hashed Password
// Checking Currrent Password Identity With Decrypted Password
if (password_verify($old_password, $password_hash)) { // Old Password And Current One Are The Same
$encrypted_password = password_hash($new_password, PASSWORD_DEFAULT); // Hashing New Password
$stmt = $this->conn->prepare("UPDATE user
SET user.`encrypted_password` = ?, user.`updated_at` = NOW()
WHERE user.`unique_id` = ?");
$stmt->bind_param("ss", $encrypted_password, $user_unique_id);
$result = $stmt->execute();
$stmt-close();
// Checking For Succesfull UPDATE
if ($result) {
$stmt = $this->conn->prepare("SELECT user.`updated_at`
FROM `user`
WHERE user.`unique_id` = ?");
$stmt->bind_param("s", $user_unique_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc(); // Fetching Rows From Query
$stmt->close();
return $user;
}
} else { // Old Password And Current One Are Different
return false;
}
}
}
Edit
Here is my database screenshot:
My script runs but it always return false which means password_verify() returns false.
Solved
The problem was $stmt->close() statement. I used them too often and thats why the script didn't work.
After debugging with #anton86993 in a chat, we found the bug to be the use of too many $sql->close() statements, when they weren't needed.
There is no reason to have that many close statements, as PHP automatically closes the connection to SQL when the script is done. A reason to have a close statement could be to release a connection to SQL, if you have a limited amount of connection at once or the obvious one to release resources.
This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
I'm trying to learn the logon coding and below in the 1st attempt it was working fine except I realize I could just use a userID login and any other password to login successfully.
I try to strengthen the logon process in the 2nd attempt but encounter the error message below. I couldn't figure out where I'm getting it wrong.
There is the $username & $passWD using filter_has_var to get the data from logon form. It's not shown below in the codes.
Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement
1st attempt:
<?php
$username = filter_has_var(INPUT_POST, 'userName') ? $_POST['userName']: null;
$passWD = filter_has_var(INPUT_POST, 'pwd') ? $_POST['pwd']: null;
include 'database_conn.php'; // make db connection
$sql = "SELECT passwordHash FROM users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql); // prepare the sql statement
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt); // execute the query
mysqli_stmt_bind_result($stmt, $passWDHash);
if (mysqli_stmt_fetch($stmt)) {
password_verify($passWD, $passWDHash);
echo "<p>Login successful</p>";
}
else {
echo "<p>Please try again.</p>";
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
2nd attempt:
<?php
$username = filter_has_var(INPUT_POST, 'userName') ? $_POST['userName']: null;
$passWD = filter_has_var(INPUT_POST, 'pwd') ? $_POST['pwd']: null;
include 'database_conn.php'; // make db connection
$sql = "SELECT * FROM users WHERE username = ? AND passwordHash =?";
$stmt = mysqli_prepare($conn, $sql); // prepare the sql statement
mysqli_stmt_bind_param($stmt, "ss", $username, $passWD);
mysqli_stmt_execute($stmt); // execute the query
mysqli_stmt_bind_result($stmt, $username, $passWDHash);
if (mysqli_stmt_fetch($stmt)) {
password_verify($passWD, $passWDHash);
echo "<p>Login successful</p>";
}
else {
echo "<p>Sorry please try again.</p>";
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
using the wildcard * is not recommend. probably there are more columns in the table than just the 2 you need?
maby something like:
SELECT username,passwordHash FROM users WHERE username = ? AND passwordHash =?
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I'm receiving the following error from the PHP compiler-
Parse error: syntax error, unexpected 'else' (T_ELSE) in C:\wamp\www\project alpha\functions.php
I've commented the else statement with-//ERROR ON THIS ELSE STATEMENT in the code below. But I can't work out why it is failing.
Can you see a problem with the code?
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli - > prepare("SELECT carer_id, username, password
FROM carers
WHERE email = ?
LIMIT 1")) {
$stmt - > bind_param('s', $email); // Bind "$email" to parameter.
$stmt - > execute(); // Execute the prepared query.
$stmt - > store_result();
// get variables from db result.
$stmt - > bind_result($user_id, $username, $db_password);
$stmt - > fetch();
if ($stmt - > num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the plain textpassword verified against hashed password in the database (not ==)
if (password_verify($password, $db_password)) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = password_hash($db_password.$user_browser, PASSWORD_BCRYPT);
// Login successful.
return true;
} else { //ERROR ON THIS ELSE STATEMENT
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli - > query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
The previous else part is not ended before this else. Close the previous else.
.............
} else {
// Check if the plain textpassword verified against hashed password in the database (not ==)
if (password_verify($password, $db_password)) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = password_hash($db_password . $user_browser, PASSWORD_BCRYPT);
// Login successful.
return true;
}
} else { //ERROR ON THIS ELSE STATEMENT
// Password is not correct
// We ...............