0

I'am currently making a login system for news website as part of my coursework. For some reason when I use $rows->num_rows == 1 in an if statement, it always runs the "else" code. Basically this means that it doesnt detect a row in my table that corresponds with the correct user information being inputed... Here is the PHP code that is ran when any information is input into the html form.

<?php
error_reporting(E_ALL);  
ini_set('display_errors', 1); 

//Connect to DB
    include_once("db_connect.php")or die ("Couldnt connect to DB");
$username = $_POST['user'];
$password = $_POST['password'];

session_start();

if(trim($username) != '' and trim($password) != ''){

//Sanitizes whatever is entered 
    $username=stripslashes($username);
    $password=stripslashes($password);

    $username=strip_tags($_POST['user']);
    $password=strip_tags($_POST['password']);

    $username=mysqli_real_escape_string($conn,$username);
    $password=mysqli_real_escape_string($conn,$password);

//Checks whether Username exists        
 $query = mysqli_query($conn, "SELECT * FROM user WHERE users='$username'  
 AND password = '$password' ")
 or die(mysqli_error($conn));

$numrows=mysqli_num_rows($query);

if($numrows > 0){

// echo "Record exists.";

$_SESSION['login_user']=$username; // Initializing Session

header("location: index.php"); // Redirecting To Other Page
exit;
}   

else {
    echo "Username or password is incorrect.";
}
}else{  
    echo "Please enter information";
}
?>

The problem occurs at the last if statement as it never detects a row. And yes, my table is populated with 1 row of user information (user,password) and my HTML form also uses POST.

I have researched this issue for at least 3 hours and still cant find a resolution.

Here are the current error logs:

Warning: include_once(1): failed to open stream: No such file or directory   in /home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 6

Warning: include_once(): Failed opening '1' for inclusion  
(include_path='.:/usr/share/pear/') in     
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 6

Notice: Undefined variable: conn in     
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 22

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null    
given in /home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line   
22

Notice: Undefined variable: conn in  
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 23

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null   
given in /home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 
23

Notice: Undefined variable: conn in  
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 42

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in     
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 42

Notice: Undefined variable: conn in 
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 43

Warning: mysqli_error() expects parameter 1 to be mysqli, null given in 
/home/vol9_7/byethost4.com/b4_18083024/htdocs/loginAuth.php on line 43

EDIT: Using Fred -ii- answer. include_once("db_connect.php")or die ("Couldnt connect to DB"); has now been moved to the top of the code.

Secondly, a new if statement has been added to replace the older version. This statement can also be found in Fred -ii- answer.

Thirdly, SQL statement has been fixed since I was mixing up the table and column name.

Lastly, error_reporting(E_ALL); ini_set('display_errors', 1); has been added to help find errors, again courtesy of Fred -ii- answer.

6
  • give if ($rows->num_rows >= 1) a whirl. I'm betting on a duplicate username or your query failed. Commented May 17, 2016 at 19:24
  • oh btw that include_once("db_connect.php") is in the wrong spot which my above comment should probably be used also if ever there are more than one username bearing the same name, but you need to connect first before using that escape function. You're putting the carriage before the horse here and NOT checking for errors whatsoever. Commented May 17, 2016 at 19:25
  • do you have duplicated records in database ? Move the include_once("db_connect.php") on the first line of php document Commented May 17, 2016 at 19:28
  • ^ I said that already. Commented May 17, 2016 at 19:28
  • Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Make sure that you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding. Commented May 17, 2016 at 19:40

2 Answers 2

1

The below answer was posted as per your original post https://stackoverflow.com/revisions/37284594/1 and without marking it as an edit and moved the include at the top of your code twice, and without marking them as additional edits.


You're putting the carriage before the horse here

include_once("db_connect.php")or die ("Couldnt connect to DB");

it needs to be placed before you call any function that requires a db connection, being mysqli_real_escape_string().

You should also use if ($rows->num_rows >= 1) or if ($rows->num_rows > 0) should there be more than one person bearing the same username later on as your database grows; it can happen. As a matter of fact, I was testing something to that effect yesterday.

Plus, use exit; after each header, otherwise your code may want to continue to execute.

You should also check for errors against your query; you're not doing that.

If that still doesn't work, then some of the functions you're using against the POST arrays could have adverse effects and may be getting rid of valid characters. You may need to remove them.

Using a prepared statement will do away from all of those.

Error checking (your query failed).

Consult these following links http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php and apply that to your code.


Passwords

I also noticed that you may be storing passwords in plain text. This is not recommended.

Use one of the following:

Important sidenote about column length:

If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.

You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.

Other links of interest:


Edit:

Change this block: (your method may be failing for $rows->num_rows)

$query="SELECT * FROM user WHERE users='$username' AND password = '$password'";
$rows = mysqli_query($conn, $query);

if ($rows->num_rows == 1){

    $_SESSION['login_user']=$username; // Initializing Session

    header("location: index.php"); // Redirecting To Other Page
}

to:

$query = mysqli_query($conn, "SELECT * FROM user WHERE users='$username' AND password = '$password' ")
or die(mysqli_error($conn))
;

$numrows=mysqli_num_rows($query);

if($numrows > 0){

// echo "Record exists.";

    $_SESSION['login_user']=$username; // Initializing Session

    header("location: index.php"); // Redirecting To Other Page
    exit;
}

and place this at the top of your file:

<?php 
error_reporting(E_ALL);  
ini_set('display_errors', 1); 

// rest of your code

NOTA:

I'm questioning this though SELECT * FROM user WHERE users

Make sure you chose the right table and that you didn't inverse those by chance.

Sign up to request clarification or add additional context in comments.

14 Comments

So with regards to your first point. I simply need to move that line above the mysqli_real_escape_string since it uses a connection to the database?
@KentGodfrey Yes, try that. I have to leave now but will be back in about an hour. Keep me posted.
Ok, done that. I actually decided to put it above my variables. Code is updated so you can see. And regards to my issue, it hasnt been solved as of yet. Thanks for taking the time out to reply and help me. Also, I am very aware of password encryption. If this project were to ever be used seriously I would 100% use a form of encryption for any personal data. See you in an hour or so
@KentGodfrey I'm back. I noticed you went and edited your question without marking it as an edit. If I get downvoted because of it, I'll delete my answer. If it's still not working and as I stated in my answer which you need to go over it again and in its entirety, is that it failed you. Check for errors. I've used this type of code countless and successfull times. btw, I had to do a rollback to your original post.
@KentGodfrey also reload my answer and look near the bottom under Edit:. If that still doesn't work, then your query failed and again; you need to check for errors and I don't know if that is related to your unknown HTML form and its elements and whether it's using a POST method and the elements all bear the right name attributes for them.
|
0

I suggest you a different code

use this:

if ($result = mysqli_fetch_array($rows,MYSQLI_NUM)){

instead of this:

if ($rows->num_rows == 1){

3 Comments

Hmm, when I use this if statement it makes my login form always return a white page. Thanks for the input and your time!
your welcome , i forget one ")" in if statement. i fixed it. ;)
Ok, so when I use the new if statement it runs "Username or password is incorrect". I am 100% using the correct credentials . Thank you for your input once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.