PHP MYSQLi query only accesses user on first row - php

Follow the links above, in sequence, for an example of a username & password login web based system, developed using PHP, JavaScript and a MySQL database.
Follow the links above, in sequence, for an example of a username & password login web based system, developed using PHP, JavaScript and a MySQL database.
Follow the links above, in sequence, for an example of a username & password login web based system, developed using PHP, JavaScript and a MySQL database.

You are testing only the first row of the table user. When you test using the if statement, the first row returned is either the user trying to log in, or not.
Instead, you can do the following:
function user_exists($username) {
$username = sanitize($username);
$query = mysqli_query($_POST['x'], "SELECT * FROM users where username ='".$username."'");
$row = mysqli_fetch_array($query);
if(count($row)>0) {
return true;
}
else return false;
}
This looks for all rows with the given username. Of course, testing passwords or other things will depend on actually iterating through the array fetched, instead of just checking the count.

I finally did it yesterday thanks to you guys. It works well however is needed to be repeated in other functions involved (which is what failed) and yes I forgot my error reporting was turned off, making life harder for myself:
function user_exists($username) {
$username = sanitize($username);
$query = mysqli_query($_POST['x'], "SELECT `username` FROM `users` WHERE `username` = '$username'");
while($row = mysqli_fetch_assoc($query)){
$rows[] = $row;
}
if (count($rows) > 0) {
return true;} else return false;
}
Same done for the login function:
function login($username, $password){
$username = sanitize($username);
$password = md5($password);
$query = mysqli_query($_POST['x'], "SELECT `userid` FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
while($row = mysqli_fetch_array($query)){
$rows[] = $row;
}
if(count($rows) > 0) {
$userid = user_id_from_username($username);
return $userid; } else return false;
Thanks again!

Related

mysqli_fetch_array($result, MYSQLI_NUM);

This mysqli_fetch_array not returning values. Checked it for SQL errors, none found. some error in PHP or functions I guess. Please help me correct it.
$login = login($username, $password);
if ($login == false) {
$errors[] = "That username and password combination is incorrect";
}
// validate login
function login($username, $password){
$user_id = id_from_username($username);
echo $user_id;
$password = md5($password);
$username = sanitize($username);
$query = "SELECT `password` FROM `user_data` WHERE `username` = '$username' ";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
if ($row[0] == $password) {
echo "Login successful";
return $user_id;
}
else{
echo "Login not successful";
return false;
}
}
// user id from username
function id_from_username($username){
$username = sanitize($username);
$query = "SELECT `user_id` FROM `user_data` WHERE `username` = '$username'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
return $row[0];
}
EDIT: As Lawrence correctly pointed out I missed the variable scope issue. mysqli_query does not have access to $conn variable.
Try to check the number of returned rows in the $result:
echo $result->num_rows;
Or print it to the log if you have some. Not sure how you are checking mysqli_fetch_array does not return values - try var_dump() or print_r().
Few further recommendations:
Both queries in your question select from the same table - user_data - it is pretty inefficient to do it separately (unless id_from_username is commonly used elsewhere), I'd merge that into one query to select it at once:
SELECT user_id, password FROM user_data WHERE ...
Using mysqli_query and concatenating user input into the query is usually a bad idea. Not sure what your sanitize function does but I'd still use variable binding instead, even mysqli supports that with mysqli_prepare, see here.
Based on your code you are storing passwords in database using md5. This is a very bad practice. PHP provides very nice functions password_hash and password_verify since PHP 5.5.0, they will handle password hashing for you and make your application a lot more secure.

assign $_session var from object

This is a login script I am working on; It uses mysqli (I know it is not as secure as PDO)
After running the MySQL query I am fetch_object(). I am then assinging $_session to hold the user ID and email. $_SESSION['uid'] = $user->ID works but not $_SESSION['uemail'] = $user->email. Could this be because of email is stored in the object $user? Do I have to convert it somehow?
email is store ass a varchar(255) in the database ID is a int(11).
<?php
include_once("config.php");
$username = $_POST['username'];
$password = sha1($_POST['password']);
$query = "SELECT ID FROM user WHERE username = '$username' AND password = '$password' LIMIT 1";
if ($result = $db->query($query)) {
while ($user = $result->fetch_object()) {
$_SESSION['uid'] = $user->ID;
$_SESSION['uemail'] = $user->email ;
header("Location: index.php");
//exit();
}
}else {
echo "Invalid login information. Please return to the previous page.";
//exit();
}
//var_dump(get_object_vars($result));
//$db->close();
?>
Thanks in advance.
Comment to answer:
You need to select the column(s) for which you are querying for:
SELECT ID, email FROM ...
which is why $_SESSION['uemail'] = $user->email ; is failing.
Either choose the specific column(s) in question, or a SELECT * would also work.
However and it's been said before, that using * isn't suggested, therefore select the actual column(s).
you are not selecting the email column from the database.
Try:
$query = "SELECT ID, email FROM user WHERE username = '$username' AND password = '$password' LIMIT 1";

Checking whether username exists or not code in sql and php

I have written a code to check whether the username exists in the database or not. It seems to return that there is no such username exists even if there's a same username existing.
$conu=mysqli_connect("localhost","db_user","db_pass","db_name");
$result = mysql_query("SELECT 1 FROM member WHERE username = $username");
if ($result && mysql_num_rows($result) > 0) {
$user_err = "<i><span class='error'>Usernme already exists</span></i>";
$errflag = true;
}
elseif(preg_match("/^[0-9a-zA-Z_]{5,}$/", $username) === 0) {
$user_err = "<i><span class='error'>Usernme must be bigger than 5 chararacters and can contain only digits, letters and underscore</span></i>";
$errflag = true;
}
Try
mysql_query("SELECT username FROM member WHERE username = '$username' LIMIT 1;");
SELECT 1 is not actually using the database; it's always returning 1, hence why your result is always the same regardless of the contents of the member table.
Usernames I take it are some sort of varchar? If that is the case, you might want to put its value in quotes:
$result = mysql_query("SELECT `username` FROM `member` WHERE `username` = '".$username."' LIMIT 1;");
your query is subject to sql injections btw.
At first, you are trying to return a column that probably doesn't exist: "1"
Second, I hope that you are cleaning the $username or else you are allowing anyone to inject your database.
The correct query is
mysql_query("SELECT * FROM `member` WHERE `username`='$username'");
You are using mysqli to connect, but mysql to perform your query.
When you SELECT 1 FROM member WHERE username = $username, the result will always be 1.
You need to put $username in the query in quotes. Something like SELECT username FROM member WHERE username = '$username'.
You forgot to include the part of the code for when there is no such username in your posting.

user login with php and mysql database

I'm new to mysql and php.
Been working on creating a database with a table for users.
I've managed to successfully add users to the database, and their passwords with md5(yea i know it's not secure), it's not going to be launched online.
My problem is, how do I log a user in, based on their correct username and password.
here is my code
My logic is taht after the query runs, it will return either true or false.
If true, then display successful login, else unsuccessful.
however, even if i input a correct username and password, i still get a unsuccessful login message
i checked the mysql database, and the uesrname is in there correctly
ideas?
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
$result = mysql_query($sql);
if ($result == true) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
I'm not entirely sure your SQL will run, but just to be on the safe side.
Change it so that
$password_hash = md5($password);
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = '$password_hash'";
And for your original question
if(mysql_num_rows($result) == 1) { //If the SQL returns one row, that means that a user was found with `userName = $username` and `password = md5($password)`
// Login
} else {
// Authentication Failed
}
Also, consider using MySQLi instead of MySQL since it has been depreciated.
First of all, protect your code against SQL injections.
Then, make sure that the password in the DB is really hashed with md5() function.
Make sure you form uses POST method to pass the data to the script.
Try the following code:
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '". addslashes($username) ."' AND password = '". md5('$password')."'";
$result = mysql_query($sql);
if (mysql_num_rows($result)>0) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
mysql_query doesn't return TRUE or FALSE. Per the docs (http://php.net/manual/en/function.mysql-query.php), it returns a resource if successful, or FALSE if there is an error. You need to evaluate the resource to see if it's valid.
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
$result = mysql_query($sql);
if ($result && $row = mysql_fetch_assoc($result)) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
As mentioned in my comment, the issue seems to be your sql string. Instead of hashing, you are putting the method into the string. So change
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
to
$sql = "SELECT * FROM `users` WHERE userName ='$username' AND password = '".md5('$password')."'";
Your result will not be true or false, but since php treats any value not a 0 as true, it will work as is.
Also, it is strongly recommended to escape all data going into your sql string to prevent sql injection. Another note: mysql is being deprecated, so now would be a great time to move to something like mysqli.

mysql - fetching data from table row

I have gotten a snippet of code to bring back the username and password and see if they match. i now want to set a session varaible to the 'points' value i have in the table which is in the same row as the username and pass.. what could be done?
<?php $username="asdin";
$password="1sdA2";
$database="a75sdting";
$pword = $_REQUEST['pword'];
$uname = $_REQUEST['uname'];
mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
$exsists = 0;
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
break;
}
if ($exsists){
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}
mysql_close();
?>
i want to set $_SESSION['points'] = $row[points] i guess... but i dont think that is correct
<?php
// start session (required on every page that uses sessions
session_start();
// db auth
$username="asdin";
$password="1sdA2";
$database="a75sdting";
// user auth
$pword = $_POST['pword']; // should use either $_POST or $_GET, NOT $_REQUEST
$uname = $_POST['uname']; // should use either $_POST or $_GET, NOT $_REQUEST
// open db connection
$conn = mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database,$conn) or die( "Unable to select database");
// check user
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
if(mysql_num_rows($query)){
// user exists
$row = mysql_fetch_assoc($query);
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}else{
header('Location: http://wwsdipts/login.php'); // take them back to login page if incorrect details
}
// close db connection
mysql_close($conn);
?>
I've tidied up your code a bit, please take a look at the notes. It is also worth nothing the following:
You should be using some sort of protection against SQL injections, such as mysql_real_escape_string($_POST['uname']) - the same for password
You need session_start() on all pages that use session variables
You shouldn't use $_REQUEST, use either $_POST or $_GET (read about it)
Do you actually have a table named username? You should read up a bit about DB design, a better name/use for this table would be users as the table will be holding users (a combination of unique ID, username & password.
I don't know what you mean about points, but to access any column name in the "username" table, use $row['column-name'] after it is set ($row = mysql_fetch_assoc($query);)
If you intend on using PHP a lot in the future, you should look up PDO, it's a great class for handling SQL.
you are right, but in this case your array is rows, and it should be in
$_SESSION['points'] = $rows['points']
And it should be in your while loop:
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
$_SESSION['points'] = $rows['points']
break;
}
However, it might be better to do something like this:
if(mysql_num_rows($result) == 1) {
//Login Successful
rows = mysql_fetch_assoc($result);
$_SESSION['points'] = $rows['points']
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}

Categories