Mysqli_prepare not working - php

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);

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);
?>

Checking and deducting points using php/mysql

This is probably a very simple problem for you geniuses. I am trying to use a php code to check my database, to see if a user has enough points. Then if they have enough points, then deduct the points from there account.
This is what I'm currently using that is not working:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$response = array();
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $_POST["username"]);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $username, $password, $points);
$pointsint = (int)$points;
if ($pointsint > 12500){
$statement = mysqli_prepare($con, "UPDATE user SET points = points - ? WHERE username = ?");
mysqli_stmt_bind_param($statement, "is", 12500, $_POST["username"]);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $username, $password, $points);
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["username"] = $username;
}
}else{
$response["success"] = false;
}
echo json_encode($response);
?>
You could probably do that in SQL without the first SELECT command like:
UPDATE `user` SET `points` = (
CASE
WHEN `points` > 12500 THEN `points` = `points` - ?
ELSE `points`=`points`
END
) WHERE username = ?

Cannot get Login to work on Android

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.

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