This question already has answers here:
MySQL password function
(4 answers)
Closed 2 years ago.
I am making a php document the logs the user in if they are in the database and entered the correct username and password. To be secure I am using prepared statements but I can't get the results from my SELECT query to set session variables necessary for my site. Here is my code...
<?php
session_start();
require 'config.php'; #This file has all connection info
#$C is the mysqli connection
#$USERS is the name of the table in my database
$sql = $C->prepare('SELECT ID,Username,Favorites FROM '.$USERS.' WHERE Email=? AND Password=PASSWORD(?)');
$sql->bind_param("ss", $e,$p);
$e = $_POST['e'];#email
$p = $_POST['p'];#password
$query = $sql->execute();
$sql->store_result();
$numrows = $sql->num_rows;
if($numrows == 1) {
$sql->bind_result($id,$username,$favs);
while($sql->fetch()) {
$_SESSION['ID'] = $id;
$_SESSION['Name'] = $username;
$_SESSION['favs'] = $favs;
$_SESSION['valid'] = true;
}
echo 'true';
}
else {
echo 'User Not Found';
}
This just echoes 'User Not Found' because $numrows always = 0 and I made sure that all the entered info was correct.
Move the variable assignments to $e and $p above the call to bind_params or at least declare them above the call.
The parameters to bind_params are passed by reference, so changes to the variables after bind but before execute take effect, but AFAIK the variables have to exist before the bind call.
Related
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have created a login page however I'm having a hard time authenticating the user. I am able to establish a connection however my sanitation is not working. I'm not sure if its the select statement or HTML related. I've played around with different SELECT statements and troubleshooted the code further up but that doesn't seem to be the problem.
<?php
// Now I check if the data from the login form was submitted, isset() will check if the data exists.
if (!isset($_POST['username'], $_POST['user_password'])) {
echo 'error2';
// Could not get the data that should have been sent.
exit('Please fill both the username and password fields!');
}
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare("SELECT id, username, user_password FROM user_info WHERE username = ?")) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
// Store the result so we can check if the account exists in the database.
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $user_password);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to store the hashed passwords.
if (password_verify($_POST['user_password'], $user_password)) {
// Verification success! User has loggedin!
// Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = true;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
} else {
echo 'error3';
}
You're selecting 3 columns in SELECT id, username, user_password but you're only binding two variables in $stmt->bind_result($id, $user_password);. This mismatch will cause an error.
There's no need to select username since that's the column you're matching in the WHERE clause. Change the select list to SELECT id, user_password to match the variables you're binding.
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.
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 6 years ago.
I want to check if a user already exists.
I made the following code but it is not working.
The echo in the checkUser is only to look if it jumps in the if clause.
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$checkUserID = mysql_query("SELECT *
FROM users
WHERE username = '$username'");
if (mysql_num_rows($checkUserID) >= 1) {
//echo "User id exists already.";
echo "testststst";
$user1 = mysql_fetch_array($checkUserId);
$result = flashMessage("User is already taken, please try another one");
//print_r($user); // the data returned from the query
}else if(empty($form_errors)){
...formcheck...
}
I hope somebody can help me I don't know what to do.
I suggest you tu use PDO library. For your problem the best solution is to have the username in the table as PRIMATY KEY or with a UNIQUE CONSTRAINT. This way, if you try to insert two times the same username, the query will throw an exception (or will return false depending how you set it) and it's easier to do.
I can see the following problems with your code--
You haven't made any database connection.
You should check whether the $_POST variables are available or not. That is try to use if(isset) function to check it.
Try using prepared statements as they are more secure.
first of all ur code is vulnerable to sql injections. Wrapped the form data with the function.
<?php
//function to prevent sql injections
function validateFormData($formData) {
$formData = trim( stripslashes( htmlspecialchars( strip_tags( str_replace( array( '(', ')' ), '', $formData ) ), ENT_QUOTES ) ) );
return $formData;
}
$email = validateFormData($_POST['email']);
$username = validateFormData($_POST['username']);
$password = validateFormData($_POST['password']);
$checkUserID = mysql_query("SELECT *
FROM users
WHERE username = '$username'");
if (mysql_num_rows($checkUserID) >= 1) {
//echo "User id exists already.";
echo "testststst";
while ($row = mysqli_fetch_assoc($checkUserID)){
//set some variables to save some data
$usernameD = $row['username'];
}
//compare form username with db username{
if($usernameD === $username){
echo "Username already taken";
}else{
//continue the rest...
}
}
?>
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.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
i make PHP site
With USER / Pass Login
But USer can Skip This Page BY Use
'=' 'or'
‘ or 1=1
Like this
Code Here In File Login_Check.php
`
include("includeszzz/host_conf.php");
include("includeszzz/mysql.lib.php");
$obj=new connect;
$obj1=new connect;
$username=$_GET["username"];
$password=$_GET["password"];
//echo $username;
//echo $password;
$sql="select username from admin where username='$username'";
$obj->query($sql);
$U_num=$obj->num_rows();
//echo $U_num;
if($U_num!=0) {
$sql1="select password from admin where username='$username' and password='$password'";
$obj1->query($sql1);
$P_num=$obj1->num_rows();
if($P_num!=0) {
session_start();
$_SESSION["zizo"]="$username";
//header("location: welcome.php");
echo "1";
} else {
echo "Invalid Password Please Try Again";
}
} else {
echo "Invalid Username Please Try Again";
}
`
You want to avoid using user data in queries without any type of sanitation.
http://php.net/manual/en/security.database.sql-injection.php
"Example #5 A more secure way to compose a query..."
<?php
settype($offset, 'integer');
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// please note %d in the format string, using %s would be meaningless
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
$offset);
?>
If the database layer doesn't support binding variables then quote
each non numeric user supplied value that is passed to the database
with the database-specific string escape function (e.g.
mysql_real_escape_string(), sqlite_escape_string(), etc.). Generic
functions like addslashes() are useful only in a very specific
environment (e.g. MySQL in a single-byte character set with disabled
NO_BACKSLASH_ESCAPES) so it is better to avoid them.
Do not print out any database specific information, especially about
the schema, by fair means or foul. See also Error Reporting and Error
Handling and Logging Functions.
You may use stored procedures and previously defined cursors to
abstract data access so that users do not directly access tables or
views, but this solution has another impacts.
Additionally, you can make use of Binding Parameters:
http://php.net/manual/en/pdo.prepared-statements.php
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>