My code works but it only works for the first row. When I insert another row in MySQL and try and log-in with the different username and password it returns my error. What's wrong?
<?php
include_once('db.php');
$username = $_POST['username'];
$password = sha1($_POST['password']);
if(!empty($username) && !empty($password)) {
$loginSQL = "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'";
if($db->query($loginSQL)->fetchColumn() == 1) {
$fetchUsers = $db->query($loginSQL)->fetch(PDO::FETCH_ASSOC);
$userID = $fetchUsers['uid'];
$_SESSION['uid'] = $userID;
echo '<br /><br />You have successfully logged in. Click here to proceed.';
}
else {
echo '<br /><br />You have entered invalid log-in information.';
}
}
else {
echo '<br /><br />You have entered invalid log-in information.';
}
?>
Two biggest problems are double fetch and lack of prepared statements.
<?php
include_once('db.php');
if(!empty($_POST['username'])) {
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT uid FROM `users` WHERE `username` = ? AND `password` = ?";
$stm = $db->prepare($sql);
$stm->execute(array($username,$password);
if($row = $stm->fetch()) {
$_SESSION['uid'] = $row['uid'];
}
}
There are a few problems here.
fetchColumn() returns the first column of the first row, which might or might not be 1 depending on how the DB table is set up.
fetch() returns the current row the PDOStatement row pointer is on. If you don't send it to the next row, it won't move.
You are sending the same error for two different reason, helping to lead to confusion.
What would really help you is if you would restructure your code like #Your Common Sense shows and look at it then. It will help yourself better see the problem.
Related
I just started working with php and I'm not really good at it.I need to verify my user's password and username after they passed that I want to start an session with that users user_id. But everytime I try to echo the user_id I just get nothing back. hope someone can help me with this. is my code:
<?php
require_once "config.php";
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
if (strlen($username) > 0 && strlen($hash) > 0){
$query = "SELECT user_id FROM keep_user WHERE username = '$username' AND password = '$hash'";
$result = mysqli_query($conn , $query);
if($conn->query($query) == TRUE){
if(password_verify($password, $hash)){
session_start();
$_SESSION['user_id'] = $user_id;
echo $user_id;
echo "succes";
}else{
echo "error-1".$conn->error;
}
}else{
echo "error-2".$conn->error;
exit;
}
}else{
echo "error".$conn->error;
exit;
}
?>
It does echo success so I am guessing that part is good but why can't retrieve user_id?
Problem is not with password_verify function . Problem is with mysqli_query because you execute your query two times
$result = mysqli_query($conn , $query);// first time
if($conn->query($query) == TRUE){// second time
Just comment or remove $result = mysqli_query($conn , $query);// first time
To get user id form query you need to fetch it as
if ($result = $conn->query($query)) {
/* fetch associative array */
$row = $result->fetch_assoc() ;
$user_id=$row["user_id"];
$_SESSION['user_id'] = $user_id;
}
And session_start(); at the top of your page.
You script is open for sql injection Read How can I prevent SQL injection in PHP? to prevent it
I have been through quite some different codes on this site. To find what wrong with my code. Basically I just want to search in a table and test the result. I wrote something like this:
<?php
ob_start();
session_start();
$conn = new mysqli('localhost','username','password','mytable');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$valuetotest = 'something';
$result = mysql_query("SELECT id FROM members WHERE UserName = $valuetotest");
if(mysql_num_rows($result) == 0)
{
echo "User not found";
}
$password = 'something2';
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
if($password != $userData['Password'])
{
echo "Password not found";
}else{ // Redirect to home page after successful login.
header('Location: welcome.php');
}
?>
And I get always the message :
"User not found." and "password not found."
when I know the username and password are in the table...
No I'm quite knew with PHP/MySQL so there might be something quite big right in front of my face and I can't see it!!!!
Can somebody help please. Thanx.
Takes less than a second to spot. (If you had error reporting on it would take even less than that)
1) Your connection is mysqli but your query call is mysql
$result = mysql_query("SELECT id FROM members WHERE UserName = $valuetotest");
2) Value of $valuetotest is a string value and needs to be within quotes in your query. Should be like
SELECT id FROM members WHERE UserName = 'hellohi'
And not like
SELECT id FROM members WHERE UserName = hellohi
And Oh, How can I prevent SQL injection in PHP?
<?php
$result = mysqli_query("SELECT `id`, `Password` FROM `members` WHERE `UserName` = '$valuetotest'");
if(mysqli_num_rows($result) == 0)
{
echo "User not found";
}
$password = 'something2';
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
if($password != $userData['Password'])
{
echo "Password not found";
}else{ // Redirect to home page after successful login.
header('Location: welcome.php');
}
?>
You are selecting a text so you should use ' ' Symbols in your Select statement.
Like this:
$valuetotest = 'something';
$result = mysql_query("SELECT id FROM members WHERE UserName = '$valuetotest'");
$result = mysql_query("SELECT id FROM members WHERE UserName = '".$valuetotest."'");
Im trying to do a login system for my website and I changed around how it is implemented and it broke, whenever I try to login with a correct login it fails to take me to the next page, here is my php:
<?php
//finds the correct database
$sql_link = mysqli_connect("localhost", "root" , "12buckle", "GameData");
if (mysqli_connect_errno())
{
echo "Failed to connect to databse: " . mysqli_connect_error();
}
if (isset($_POST['Username']))
{
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
//checking to see if password and username can be found in student database
//loading in correct data
$login = mysqli_query($sql_link,"SELECT * FROM tblStudents WHERE UserName='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['StudentFirstName'];
$_SESSION['ClassID'] = $login['ClassID'];
$_SESSION['ID'] = $login['StudentID'];
header ("Location: index.php");
}
else
{
$login = mysqli_query($sql_link,"SELECT * FROM tblTeacher WHERE Username='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['TeacherSurname'];
$_SESSION['title'] = $login['Title'];
$_SESSION['ID'] = $login['TeacherID'];
header ("Location: TeacherSide.php");
}
else
{
echo 'Login details incorrect';
}
}
}
Also if it helps when I ran it last night im sure it worked, but I was half awake so I may have been testing the old version
Your logic is faulty. mysql_query returns a result HANDLE. it does not return any actual data. You need to fetch a row first, before checking for actual data:
$result = mysqli_query($sql_link, "SELECT * FROM tblStduents ....");
if (mysqli_num_rows($result) > 0) {
... got a student record
$row = mysqli_fetch_assoc($result);
echo $row['StudentFirstName'];
} else {
... no student rows, repeat with teachers
}
I've had issues in the past where variables aren't read properly the way you have them in your SQL statements.
Try Username='" . $username . "' AND instead and see what happens.
For some reason inputs in my login page don't seem to be getting processes correctly. Correct user inputs are getting returned as invalid (wrong password) having had a look through, I can't see anything particularly obvious. But I can only assume the username or password isn't getting passed for some reason. Would someone more experienced be able to take a look and suggest how I can put it right. Thanks guys. P.S My form is OK, so not included.
function logcon($user, $password )
{
$user = mysqli_real_escape_string($this->conn, $user);
$esc_password = mysqli_real_escape_string($this->conn,$password);
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
$result = mysqli_query($this->conn, $sql);
$row = mysqli_fetch_array($result);
return $row;
}
Login page.
if(isset($_POST['submit'])){
$user=$_POST['user'];
$password=$_POST['password'];
//To ensure that none of the fields are blank when submitting the form if
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = stripslashes($user);
$password = stripslashes($password);
$db1=new dbmember();
$db1->openDB();
$row=$db1->logcon($user, $password);
if($row[0]==1)
{
session_start();
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
$_SESSION['loggedin'] = "true";
header("location:index.php");
}
else
{
print ('<div id="error">Acess denied, wrong username or password?</div>');
}
}
else
{
print ('<div id="error">Enter something!</div>');
}
}
It appears you are using the wrong variable name in your query. I would also suggest you look into doing some sort of hashing and salting of your passwords instead of saving them as plain text.
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$password}'";
should be
$sql = "SELECT * from USERS WHERE username ='{$user}' AND password='{$esc_password}'";
And your conditional check seems off, you are checking to see if the first field in the results is = 1 instead of seeing if there is a return.
if($row[0]==1)
Should probably be
if($row)
This is my code
$username = $_POST['user'];
$password = $_POST['pass'];
if (isset($_POST['user'])); {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")){
while($row = mysqli_fetch_assoc($query)){
$row['pass'] = $setpassword;
}
mysqli_free_result($query);
}
}
What it currently does is from a form, retrive a username and password that the user has entered, take that username and find the row with that username and get the password from that row and set it as the variable $setpassword. Below is the code to check if the password matches the given username on the database.
if ($password=='') {
$verify = 0;
}
if ($password!='') {
if ($password!=$setpassword) {
$verify = 1;
}
if ($password==$setpassword) {
$verify = 2;
}
}
If verify is...
0 - The Login Form Will appear as nothing has been entered.
1 - Incorrect Password will be displayed along with the login form.
2 - Correct Password will be displayed and the username will be assigned to a session variable.
I'm having a problem where a user can enter a username that doesnt exist and any password wether its in the database or not and it will be verified.
What can I do to check if the username doesn't exist on the database?
When you are accepting the user's registration query the database to see if it already exists.
$result = mysqli_query("SELECT * FROM accounts where `user` = $username");
if(mysql_num_rows($result) >0) // if there are any rows returned then the username exists
{
//User Name already exists
}
else
{
//User name doesn't exist, add user
}
I'm not sure this is where you are doing that. But to eliminate duplicates you can do it that way. Also, you can define the column user as unique. That way the SQL will not allow duplicate values.
Also this line:
$row['pass'] = $setpassword; //setting $row['pass'] to $setpasswords value.
This is reversed. You should be doing it the other way around.
$setpassword = $row['pass']; //setting setpassword to $row['pass'] value.
Let me know if I need to clarify anything.
Try this:
$username = isset($_POST['user'])?$_POST['user']:''; // check if isset to avoid notice
$password = isset($_POST['pass'])?$_POST['pass']:'';
$verify = 0;
if (!empty($username)) {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")) {
while($row = mysqli_fetch_assoc($query)){
$setpassword = $row['pass'];
break; // exit the loop once you found the password
}
mysqli_free_result($query);
}
if (isset($setpassword)) {
$verify = 1;
if ($password == $setpassword) {
$verify = 2;
}
}
if (isset($_POST['user'])); {
there is an extra semicolon in this line, making whole code not working
to do your verification, all you need is to retrieve the password and compare it with entred one:
$row = mysqli_fetch_assoc($query));
if ($row AND $row['pass'] == $password)
$verify = 1;
}
note that $row could be ampty, so, you have to check it first
however, you can do both comparisons in the query, like this
"SELECT * FROM accounts where `user` = $username" AND `pass` = '$password';
However, your code suffers from 2 common problems.
It is better to save a hash instead of the plain password.
You should sanitize your data before adding it in the query
at least this way:
$username = mysqli_real_escape_string($db,$_POST['user']);