How to fix mysqli updating wrong value in db? - php

I'm setting up a password change script for php. All variables are in the function updatePasswordInDatabase($password, $email) { ..}.
I've triple checked that the values that the function receives are correct.
For the insertion in the database (mysql) i'm using mysqli with prepared statements.
For example, I'm inputting:
$2y$12$X/jIjlqpWfSSMg70u0RE8O0VWH3ocqychlUPy7CSG2vMhkj/F5d.q
(as $password) along with:
test#test.com ($email).
I get those values in the function correctly.
However after the update, i'm getting a different value in the password column:
i1VjH4sRf5nqv3tnShnXNTSX57jRGnbZJt7w0VLX49nZdKRsRT
What am I doing wrong?
Thanks
function updatePasswordInDatabase($password, $email) {
require $mysql;
$stmt = $conn->prepare('UPDATE `users` SET Password = ? WHERE Email = ?');
$stmt->bind_param("ss", $password, $email);
$stmt->execute();
}

Related

Trying to update a field in my DB using a prepared statement

I have been on this all day and after searching many websites (including this one) i came to the conclusion that my question hasn't been asked before probably due to my incompetence.
I have a prepared statement here that i would like to update my password field in my DB depending on the username and email, the reason it is updating and not inserting is because its part of my security to not approve site photographers until they have been sent a link
<?php
if (isset($_POST['approved-photographer'])) {
require 'dbh.php';
$username = $_POST['username'];
$email = $_POST['mail'];
$password = $_POST['password'];
$password2 = $_POST['password-repeat'];
if (empty($username) || empty($email) || empty($password) ||
empty($password2))
{
header("location:signup.php?error=emptyfields&username=" . $username
. "&mail=.$email");
exit();
} elseif ($password !== $password2) {
header("location:approvedphoto.php?error=passwordcheck&username=" .
$username . "&mail=" . $email);
exit();
} else {
$sql = "SELECT Password
FROM photographers
WHERE Username= '$username'
AND Email= '$email'";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location:approvedphoto.php?error=sqlerror");
exit();
} else {
$sql = "INSERT INTO photographers (Password) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location:approvedphoto.php?error=sqlerror2");
exit();
} else {
$hashedpwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "s", $hashedpwd);
mysqli_stmt_execute($stmt);
header("location:signin.php?signup=success");
exit();
}
}
}
}
Any Help would be greatly appreciated. Thanks for reading
The short answer for your MySQLi usage is you didn't bind the parameters, which you can do using mysqli_stmt_bind_param (Future readers, this last statement is now irrelevant due to edits). Overall your sql statements post-editing seem unclear, you would typically either be updating a password (in which case you need a WHERE clause so you don't update everyone's password), or you should be inserting a new user with a password.
This is a more-or-less tangential answer, but I would like to throw my hat into the ring for the use of PDO (instead of mysqli). MySQLi works with only one form of database flavor, MySQL. Additionally it allows for a much less object-oriented solution to db interactions. Here's an example of how you could accomplish this through PDO:
//specifies the driver, ip/database etc. Swap out for your ip and database used
$driverStr = 'mysql:host=<ip>;dbname=<database>;charset=utf8';
//you can set some default behaviors here for your use, I put some examples
//I left a link below so you can see the different options
$options = [
//spew exceptions on errors, helpful to you if you have php errors enabled
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
//substite what you need for username/password here as well, $options can be omitted
$conn = new PDO($driverStr, '<username>', '<password>', $options);
Link to the aforementioned attributes
Now that we've made our connection:
//I used a "named parameter", e.g. :password, instead of an anonymous parameter
$stmt = $conn->prepare("UPDATE Photographers SET password = :password WHERE Username = :username");
//with our prepared statement, there's a few ways of executing it
//1) Using #bind*
//there's also #bindValue for not binding a variable reference
//for params, PARAM_STR is default and can be safely omitted
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':username', $username);
$stmt->execute();
//2) Using execute directly
$stmt->execute(['password' => $password, 'username' => $username]);
Then, were the statement a query and not just a database update/insert, we can simply retrieve the results of the statement. By using #bindParam you can also just update the variable's values and re-execute the statement if you like, which may be useful to you for some other statements.
//see #fetch and #fetchAll's documentation for the returned data formatting
$results = $stmt->fetchAll(PDO::FETCH_OBJ); //return it as a php object
$results = $stmt->fetch(PDO::FETCH_NUM)[0]; //unsafely retrieve the first value as a number
Over the years I've found this to be much cleaner and more managable than any of the mysqli_* or even the deprecated mysql_* methods.

prevent sql injection in mysqli [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I am very new to mysqli earlier i am writing queries in mysql but mysqli is more advanced so, i am first time using it.
Below is my php code.
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$email = clean($_POST['email']);
$password = clean($_POST['password']);
//$password =md5($password);
if(empty($res['errors'])) {
$result = $mysqli->query("SELECT uid FROM users where email='$email' and password = '$password'");
if($result->num_rows == 1){
$res['success'] = true;
}
else{
array_push($res['errors'], 'Invalid login details');
$res['success'] = false;
}
}else{
$res['success'] = false;
}
echo json_encode($res);
}
clean function is not working as expected because sql queries return false if i enter username and password correct.
So, it seems like this is not valid in mysqli case.
I checked this link PHP MySQLI Prevent SQL Injection and got to know that we have to prepare query.
I can see there is an example but i am not able to understand how to prepare/bind if i have to use two or more form data.
Thanks for your time.
Updated code
$result = $mysqli->prepare("SELECT uid FROM users where email=:email and password = :password");
$result->execute([
':email' => $email,
':password' => $password]);
//$result->execute();
if($result->num_rows == 1){
//if(mysqli_num_rows($result) === 1) {
$res['success'] = true;
}
else{
array_push($res['errors'], 'Invalid login details');
$res['success'] = false;
}
As already stated in comments, you need to be consistent with your API choice. You can't mix APIs in PHP.
You started out with mysqli_*, so I'll continue with that. You had some mysql_* and PDO in there, and it might not be a bad idea to use PDO over mysqli_* - but if your server supports mysqli_*, there is nothing wrong with using that. See Choosing an API and decide for yourself (just stay away from mysql_*, it's outdated).
Using mysqli_*, you connect to the database like this (you didn't show your connection).
$mysqli = new mysqli("host", "username", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$mysqli->set_charset("utf8");
As for preventing SQL injection in it self, all you need is to use prepared statements. You can still clean or sanitize your data if there are some kind of values you don't want sitting in your tables - but that's kind of another discussion.
You also need to know if your passwords are hashed in the database. They really should be, and you should be using password_hash($password, $algorithm) and password_verify($password, $hash) if you're on PHP5.5 and above (if not, look into something like password_compat).
You need to be consistent with your hashes too, you can't insert it with md5 and selecting it with no hash. It all needs to be the same. Because if you are selecting an md5 hash, and comparing it to an unhashed string, they will be different, and the query fails.
I'm showing you an example of using password_verify(), so that means that the password stored in the database will also need to be stored with password_hash() (or your query fails).
if ($stmt = $mysqli->prepare("SELECT uid, password FROM users where email=?")) {
$stmt->bind_param("s", $_POST['email']); // Bind variable to the placeholder
$stmt->execute(); // Execute query
$stmt->bind_result($userID, $password); // Set the selected columns into the variables
$stmt->fetch(); // ...and fetch it
if ($stmt->num_rows) {
if (password_verify($_POST['password'], $password)) {
// Password was correct and matched the email!
} else {
// Password was incorrect...
}
} else {
// Accountname not found
}
}
This is just a basic example, but it will get you started. Never trust user input, use prepared statements.
You can bind more variables like so:
$stmt = $mysqli->prepare("SELECT uid FROM users where email= ? and password = ?");
$stmt->bind_param('ss', $email, $password);
/* execute prepared statement */
$stmt->execute();
As you can see, you can expand on the bind_param() function. You can also add different type of variables:
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
From: http://php.net/manual/en/mysqli-stmt.bind-param.php
First of all, I suggest you learn PDO instead of MySQLi, just because it supports more drivers.
Second, you use mysql_real_escape_string, as you might see, that is a MySQL function, not a MySQLi function.
So where you have:
$result = $mysqli->query("SELECT uid FROM users where email='$email' and password = '$password'");
You should do something like:
<?php
$stmt = $dbConnection->prepare("SELECT uid FROM users where email = :email AND password = :password");
try{
$stmt->execute([
':email' => $email,
':password' => $password
]);
}
catch(Exception $e){
echo $e->getMessage(); //Remove when putting online
}
if($stmt->num_rows){
$res['success'] = true;
}
?>
You're presently mixing MySQL APIs/functions with mysql_real_escape_string(), then num_rows and then a PDO binding method where email=:email and password = :password which seems to have been taken from another answer given for your question.
Those different functions do NOT intermix.
You must use the same one from connection to querying.
Consult: Can I mix MySQL APIs in PHP?
It looks like you're wanting to setup a login script. I suggest you use the following and pulled from one of ircmaxell's answers:
Pulled from https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
It's safer and uses a safe password hashing method, rather than what you seem to want to use is MD5 $password =md5($password); and is no longer considered safe to use now.
References:
PDO connection http://php.net/manual/en/pdo.connections.php
PDO error handling http://php.net/manual/en/pdo.error-handling.php
To check if a user exists, you can see one of my answers https://stackoverflow.com/a/22253579/1415724
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Sidenote: If you do go that route, remember to read the manuals and that your password column is long enough to hold the hash. Minimum length is 60, but they recommend 255.
It is also unclear if your HTML form does have name attributes for the POST arrays, so make sure the form is using a POST method.
http://php.net/manual/en/tutorial.forms.php
I believe I have given you enough information to get started.
What you must NOT do, is to use the above with your present code and simply patching it. You need to start over.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.

Reading email from database without # or

I'm trying to recall data from database to post later on
When someone logs in using this code:
function login($email, $password, $mysqli)
{
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt, phnumber, realname, age, sex FROM members 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 result.
$stmt->bind_result($user_id, $username, $db_password, $salt, $phnumber, $realname, $age, $sex);
$stmt->fetch();
}
}
Then I set variables for email and name using this code:
$realname = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $realname);
$_SESSION['realname'] = $realname;
$email = preg_replace("/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/", "", $email);
$_SESSION['email'] = $email;
Then when I recall all the variables using print_r($_SESSION); The email is posted without # or . for example: johnsmithyahoocom and also the name is posted without space like JohnSmith Which is undesirable. How can I make it post the right email form and space between names?
Why are you using preg_replace?
And I would recommend, if you are already using a database, to store only the users ID in the SESSION and fetch the other data from the database, when you need the users Information.
Sorry for wasting your time on this
Everything was going fine I just had to relogin to apply changes I made
/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/ is working fine and recalls the right email form from database I just had to restart the SESSION to see changed I made.

PHP - Write To MySQL Database

I'm simply writing some values to a MySQL database using the following snippets of code.
Please note, when I run SELECT queries, information is correctly displayed using echo etc.
However when I try to write to the database using INSERT, the code executes with no errors, but when I check my database there is nothing written to it.
private $db;
function __construct() {
$this->db = new mysqli('localhost', 'xyz', '123', 'testdb');
$this->db->autocommit(FALSE);
if (isset($_POST["ID"]) && isset($_POST["Number"]) && isset($_POST["Address"]) && isset($_POST["Ticket"])) {
$id= $_POST["ID"];
$number= $_POST["Number"];
$address= $_POST["Address"];
$ticket= $_POST["Ticket"];
$stmt = $this->db->prepare("INSERT INTO tickets (ID, Number, Address, Ticket) VALUES (?,?,?,?)");
$stmt->bind_param("iiss", $id, $number, $address, $ticket);
$stmt->execute();
$stmt->close()
return true
}
Any help would be greatly appreciated.
Edit
Question - Could it be something to do with write access to the database? I've checked the user account privileges and it has all privileges.
When using the insert auto_commit must be TRUE.
$this->db->autocommit(TRUE);
You've disabled autocommitting ($this->db->autocommit(FALSE);), and you're not committing anywhere explicitly. Once you close the connection, anything you inserted will be rollbacked, as if you never changed the database. Once you're done inserting, you should add a call to $this->db->commit().

how i can use the PDO results?

Hello every one i'm trying to do a login method for my website, and i'm having a small problem. I'm getting the data from PDO connection but every time im checking the password it returns false. is my variables wrong?
here is my sql query
$this->result = $this->sql->prepare('SELECT username,password FROM User WHERE username=:username AND password=:password');
$this->result->bindParam(':username', $username, PDO::PARAM_STR);
$this->result->bindParam(':password', $password, PDO::PARAM_STR);
$this->result->execute();
and here is my if statement:
$this->result=$this->result->fetch(PDO::FETCH_OBJ);
if (($password == $this->result->password) && ($username == $this->result->username)){
i'm not getting error it just return always false. i'm not encrypting the password yet so is not this problem. i think $this->result->password is the problem. can anyone correct me please?
thank you
You can use this as well:
$username=$_GET['username'];$password = $_GET['password'];/*of $_POST, depending of which you used*/
$this->result = $this->sql->prepare('SELECT username,password FROM User WHERE username='$username' AND password='$password');
$this->result->execute();
And then use fetchAll like this:
$this->results = $this->result->fetchAll(PDO::FETCH_ASSOC);
if($this->results['username']==$this->username && $this->results['password']==$this->password){/*u had beed loged in*/}
Your logic should work. Most likely, the SQL is not returning anything. Try printing out the result of your fetch.
$this->result=$this->result->fetch(PDO::FETCH_OBJ);
print_r($this->result);
Also, if you are checking for username and password in the SQL query, you don't have to check it again in the if statement. With the SQL statement you are using, you should be able to just check if it returned a row or not to validate the user.
$numrows = $this->result->rowCount();
if ($numrows == 1) {
// User is valid
}
else {
// User is not valid
}

Categories