I have written a script in php to reset user's password, and how do I check if password is updated in a table?
For example, if a data in the tuple/column has been changed, then send email. Please check comments in the script.
$dbcc = mysqli_connect(HOST,NAME,PASSWORD,DATABASE) or die('Error can not connect to database');
$query = "SELECT uid,email FROM `corporate` WHERE (email='$chk_email')";
$result = mysqli_query($dbc, $query);
//found
if(#mysqli_num_rows($result) == 1)
{
$ROW = mysqli_fetch_array($result);
$sent_email = $ROW['email']; //get email
$id = $ROW['uid']; //get uid
$new_password = generatePassword(8);//generates 8 char long random password
$enc_password = md5($new_password); //encrypt
$statement = "UPDATE corpoorate SET password=".$enc_password." WHERE uid ='$id'";
$go = mysqli_query($dbcc,$statement) or die(mysqli_error());
mysqli_close($dbcc);
/*
* HOW DO I CHECK IF PASSWORD IS UPDATED IN THE DATABASE?
* IF IT IS, SEND EMAIL
* IF $go==true does not work!
**/
if($go==true){
$sendmessage = "We have generated a new password token for you.\n Your password is reset to ".$new_password." \n Please note that this password is not secure. Once you login, please reset your password.\n ";
mail($sent_email,'Password Reset',$sendmessage,'From: address#gmail.com');
}
header("Location : http://limozoor.com/login/signin.php");
exit();
}//if
mysqli_close($dbcc);
Why don't you use mysqli_affected_rows?
// remove: $go = mysqli_query($dbcc,$statement) or die(mysqli_error());
$qry =# mysqli_query($dbcc, $statement);
$aff =# mysqli_affected_rows($dbcc);
if ($qry === true && $aff > 0) {
mail(...);
}
From manual;
mysqli_query:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
mysqli_affected_rows:
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
http://php.net/manual/en/mysqli.affected-rows.php
http://php.net/manual/en/mysqli.query.php
Because of your or die(mysqli_error());-condition the password will always be updated in the table if it reaches those lines of execution.
However, I am sceptic towards your if(#mysqli_num_rows($resultt) == 1) because if there is any error in your first SQL-query, you are supressing all error messages there (by using #), which makes me think that you never even try to execute the UPDATE statements.
Related
I am still in the process of learning PHP so forgive me for the poor code.
I am attempting to get the users first name to output once they have logged in, however nothing is returning, please may I have some help.
<?php
session_start();
$DATABASE_HOST="localhost";
$DATABASE_USER="root";
$DATABASE_PWORD="";
$DATABASE_NAME="registration";
$connection=mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PWORD, $DATABASE_NAME);
if (mysqli_connect_errno()){
//if there is an issue with connecting to the database, ends code and displays the error
die("failed to connect to server: " .mysqli_connect_error()); //kills program
}
if (!isset($_POST['email'], $_POST['pswd'])){ //checking if both fields were inputted into on the form, isset()checks if data exists
//unable to get data
die("please fill in both email and password"); //kills program
}
$email = mysqli_real_escape_string($connection, $_POST['email']); //saves input as string, preventing misinterpretation
$password = mysqli_real_escape_string($connection, $_POST['pswd']);//saves input as string, preventing misinterpretation
$SQLstatement = "SELECT * FROM users WHERE email='$email' and password='$password'"; //querys the database for match
$Queryresult = mysqli_query($connection, $SQLstatement) or die(mysqli_error($connection)); //runs the query
$rowsQueryResult = mysqli_num_rows($Queryresult);//number of 'emails' in database where the emails match
$dbFirstName=$rowsQueryResult ['firstName'];
if ($rowsQueryResult==1){//if the number of emails where a match is made, is 1
echo "Welcome $dbFirstName <br/> ";
echo "successful login. <a href='accountPage.php'>Click</a> here to access the accounts page"; //successful login, links to accounts page
$_SESSION['firstName']=$dbFirstName;
}else{ //if matches are 0 or >=2
die ('unsuccessful login'); //kills program
}
?>
Thank you for your time and help
This problem can be solved by using the mysqli_fetch_assoc() function in place of mysqli_num_rows(). However, I would recommend you to use PDO since it's easier to implement and more readable.
The mysqli_num_rows() function returns the number of rows in a result set.
$rowsQueryResult = mysqli_num_rows($Queryresult);`
will give number of 'emails' in database where the emails match.
You need to use mysqli_fetch_assoc() as
$row = mysqli_fetch_assoc($Queryresult);
$dbFirstName=$row['firstName'];
This question already has answers here:
INSERT query produces "Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given"
(2 answers)
Closed 3 years ago.
I am trying to create a change password page with this php script. I want to be able to tell the user whether or not they have put in the correct username and password so that it may be changed. When I check the rows, regardless if it returns rows or not, I always get this error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given
This is my code:
<?php
$uname = mysqli_real_escape_string($conn, $_POST['uname']);
$currentpw = mysqli_real_escape_string($conn, $_POST['currentpw']);
$newpw1 = mysqli_real_escape_string($conn, $_POST['newpw1']);
$newpw2 = mysqli_real_escape_string($conn, $_POST['newpw2']);
$sql = "UPDATE USERS
SET password = '$newpw1'
WHERE username = '$uname' and password = '$currentpw'";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
if($row > 0 && $newpw1 == $newpw2){
mysqli_query($conn, $sql) or die(mysqli_error($conn, $sql));
}
else if($newpw1 != $newpw2){
echo "Passwords do not match";
}
else {
echo "Username or Password is incorrect";
}
}
?>
note: i do make a connection before hand just doesn't seem necessary to have it on here. Also if I do enter the right information it will change the password as needed but still have the error message
You need to check the number of affected rows, instead of the number of rows. The num_rows constant is the number of selected rows, while the affected_rows constant is for for insert, update and delete queries.
You also should use a prepared statement instead of injecting variables directly in the query.
Another thing you had was that you attempted to run the same query twice, if it could be run once. That doesn't make much sense.
Here's a revised version, though there's still one important thing missing: you store passwords in planintext! Which is a HUGE security issue!
Don't store your passwords in plain-text! This is not secure at all! PHP has built-in functions which you should use to handle storing of passwords, see the password_hash() function which is a lot more secure!
if (isset($_POST['newpw1'])) {
$username = $_POST['uname'];
$current_password = $_POST['currentpw'];
$newpw1 = $_POST['newpw1'];
$newpw2 = $_POST['newpw2'];
if ($newpw1 === $newpw2) {
$stmt = $conn->prepare("UPDATE users SET password=? WHERE username=? AND password=?");
$stmt->bind_param("sss", $newpw1, $username, $current_password);
$stmt->execute();
if ($stmt->affected_rows) {
echo "Password updated successfully!";
} else {
echo "Username or password is incorrect";
}
$stmt->close();
} else {
echo "Passwords do not match";
}
} else {
// Form was not sent
}
http://php.net/mysqli-stmt.affected-rows
Select query only have mysqli_num_rows()
The mysqli_num_rows() function returns the number of rows in a result set.
So use
mysqli_affected_rows($conn)
The mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query.
Working on a log in system, but i keep getting this error
//$User = 'kv96';
//$Pass = 'passkv';
//echo isValidLogin($User, $Pass);
function isValidLogin($username, $password) {
$query = mysqli_query($link,"SELECT * FROM Log_in WHERE Password = '$Pass' AND User_ID ='$User'"); //Finds the database and chooses the row
//$result = mysqli_query($query);
$row = mysqli_fetch_array($result); //Fetches the row
if($row['User_ID'] != null && $row['Password'] != null){return true;}
else{return false;}
function getUsernameRole($username) {
return "instructor";
}
mysqli_close($link);
?>
Can someone explain why this error is popping, i dont see why the query is failing?
I've noticed you commented out your $result yet you were using to fetch the database array. You should be using $query instead, or get rid of the 2 // before your $result.
Not only that, you forgot to parse $link through the parameters of your function. Therefore the query will not be successful.
Another problem, you used $pass and $user variables inside of your query, however, you have not passed them through the parameters of your function either. You must change $username to $user and so on..
I've also changed your while loop to a row count. This will save you from using unnecessary code and is way more practical; saves you doing a while loop and checking if values return null.
function isValidLogin($link, $user, $pass) { // parsing through the connection link and $user, $pass variables
$query = mysqli_query($link,"SELECT * FROM Log_in WHERE Password = '$Pass' AND User_ID ='$User'"); //Finds the database and chooses the row
$count = mysqli_num_rows($query);
if($count > 0){
return true;
} else {
return false;
}
}
A suggestion I would like to make (and HIGHLY recommend) is to use prepared statements to protect against SQL injection, however, you can find many posts on how to do that.
<?php
$con = mysqli_connect('localhost','root','[mypassword]','dbhwsource');
if(isset($_GET['username'])){
$username = $con->real_escape_string($_GET['username']);
$test = $con->query("SELECT username FROM users WHERE username='$username'");
if($test!=false) die("usererror");
}
if(isset($_GET['email'])){
$email = $con->real_escape_string($_GET['email']);
$test = $con->query("select * from users where email='$email'");
if($test!=false) die("emailerror");
}
$con->close();
echo "ok";
?>
So I'm just trying to check to see if the username / email is available or not, but all i get is "usererror" no matter what the input username is! I'm just frustrated and have searched for sample code everywhere and the code looks like there's nothing wrong with it. What am I doing wrong?
EDIT:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
This worked!
Since your query returns true, this line if($test!=false) die("usererror"); gets executed,
should be something like
$test = $con->query("SELECT username FROM users WHERE username='$username'");
$row_cnt = $test->num_rows;
if( $row_cnt > 0 ) {
//you already have user with this name, do something
}
$con->query returns a result object if the query was successful. This doesn't say anything about how many rows where found or whether the query matched anything, it just means the query executed successfully. Therefore your $test!=false test always succeeds; only in the case of a database error would it fail.
Do the query as SELECT COUNT(*) FROM ..., then fetch the first row of the result and see if the count is > 0.
I recently did something like this for an android app. you should really check this site out. It helped me tremendously. This is a detailed example of having a PHP API for an aplication. Specifically logging in.
To be specific though, here is a snippet from the page for the PHP
/*
* Check user is existed or not
*/
public function isUserExisted($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
This worked for me:
$test = $test->fetch_assoc();
if(!empty($test)) die("usererror");
Your code is really not secure not optimized anybody can login with sql injection in your code.
and your code is right as you are checking thar (test != false) it means it is true that's why your code og usererror is executing
here is some tips and always use this style for security and optimization
do same for $email
third after running the query do not check if it is true or false but check again after query
if($test->username === $_GET['username']) { do something }
check sql injections on Google why i did this
I am using mysql_num_rows to check if one row is returned for my user login and if count == 1 then log user in, I get an error though below my code is after that. Any suggestions?
Warning: mysql_num_rows(): supplied
argument is not a valid MySQL result
resource in
/home/web42001spring09/rcoughlin/public_html/process-login.php
on line 13
<?php
// include database info
include("config.php");
if(isset($_POST["submit"])){
// get data from form
$username = $_POST["user"];
$password = $_POST["pass"];
$query = "SELECT username,password,id FROM login WHERE username=".$username." AND password=".$password." LIMIT 1";
$result = mysql_query($query);
$count = mysql_num_rows($result);
// if 1 then login them in set cookie and redirect
if($count==1){
setcookie("password", "".$password."", time()+3600);
setcookie("username", "".$username."", time()+3600);
header("Location:admin.php");
}else{
echo "Wrong Username or password combination";
}
}else{
echo "Must be submitted via form.";
}
Not sure why the code is drawing that issue? I have used this method before.
You're not quoting your strings in the query, so your SQL statement is invalid.
$query = "SELECT username,password,id FROM login WHERE username='" . mysql_escape_string($username) . "' AND password = '" . mysql_escape_string($password) . "' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
You need to add quotes AND use mysql_escape_string or mysql_real_escape_string to prevent SQL injection attacks.
Firstly, check for errors...
The "supplied argument is not a valid MySQL result resource" because there was an error in your SQL, but you haven't made life easy for yourself by ignoring the failed query. Use mysql_error to get the error message.
Secondly, properly escape strings in SQL...
Once you see the error, you'll see you missed some quotes in your query, but you must also escape the strings you put in a query, otherwise you're vulnerable to SQL injection attacks...
$query = "SELECT username,password,id FROM login ".
"WHERE username='".mysql_real_escape_string($username)."' ".
"AND password='".mysql_real_escape_string($password)."' LIMIT 1";
$result = mysql_query($query);
if ($result)
{
$count = mysql_num_rows($result);
// if 1 then login them in set cookie and redirect
if($count==1){
setcookie("password", "".$password."", time()+3600);
setcookie("username", "".$username."", time()+3600);
header("Location:admin.php");
}else{
echo "Wrong Username or password combination";
}
}
else
{
echo "Error:".mysql_error()."<br>;
}
Always use mysql_real_escape_string when building a query, or use a wrapper class library which does it for you with parameterised queries, like PDO or ADODb
Finally, a word on those cookies...
Also, logging someone in by giving them a cookie with the username and password isn't a terribly good way to implement a login. Aside from transmitting the password in the clear with every request, it's highly vulnerable to a cookie theft attempt. Given your naive approach to SQL security, it's likely you'll also be leaving yourself vulnerable to XSS attacks making it easy for someone to collect those cookies :)
Looks like you might want to do 2 things:
Sanitise your input - passing user-submitted data straight into a database query is a recipe for disaster (see mysql_real_escape_string(string $unescaped_string)).
Put quotes around literals in database queries (i.e. username ='".$username."')
The error message you're getting is due to the fact that the MySQL result object ($result) is not valid. Try calling mysql_error() to see what error message MySQL returns.
Try:
$row = mysql_fetch_row($result);
if ($row) { // success
Assuming you'd probably want to fetch some columns along with the authentication check (e.g. real name, last login etc.)
Do never store user authentication data in a cookie!
Because both password and login are strings, you need to change the SQL:
$query="SELECT username,password,id FROM login WHERE username='".$username."' AND password='".$password."' LIMIT 1"
The query is invalid (the $result == false)
Line:
$query = "SELECT username,password,id FROM login WHERE username=".$username." AND password=".$password." LIMIT 1";
Should be replaced by:
$query = "SELECT username,password,id FROM login WHERE username='".mysql_escape_string($username)."' AND password='".mysql_escape_string$password)."' LIMIT 1";
The PHP mysql_query() function doesn't give errors by default.
Using a function that shows sql errors allow you to spot these errors easily.
function my_query($sql) {
$result = mysql_query($sql);
if ($result === false) {
trigger_error('['.mysql_errno().'] '.mysql_error(), E_USER_WARNING);
}
return $result;
}
Right now the username and password are injected directly in the sql string.
What you want is password = "secret", now the query contains password = secret
Mysql error "unknown column sercet"
PS:
Using a "LIMIT 1" here is a sign that there are several users (ids) using the same username password combination. (Not recommended)