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.

Kent Godfrey
  • 83
  • 1
  • 3
  • 12
  • give `if ($rows->num_rows >= 1)` a whirl. I'm betting on a duplicate username or your query failed. – Funk Forty Niner May 17 '16 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. – Funk Forty Niner May 17 '16 at 19:25
  • do you have duplicated records in database ? Move the include_once("db_connect.php") on the first line of php document – Andrei Todorut May 17 '16 at 19:28
  • ^ I said that already. – Funk Forty Niner May 17 '16 at 19:28
  • **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure that you **[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard May 17 '16 at 19:40
  • @JayBlanchard I will keep that in mind. As for now, this project is in early development therefore im trying to just get the core working. – Kent Godfrey May 17 '16 at 21:39

2 Answers2

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.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • 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? – Kent Godfrey May 17 '16 at 19:39
  • @KentGodfrey Yes, try that. I have to leave now but will be back in about an hour. Keep me posted. – Funk Forty Niner May 17 '16 at 19:40
  • 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 – Kent Godfrey May 17 '16 at 19:42
  • @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. – Funk Forty Niner May 17 '16 at 20:38
  • @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. – Funk Forty Niner May 17 '16 at 20:49
  • sorry for not marking it as an edit.Do I just fill out the edit summary? I am sure I did it. Also, you were correct about my query. I have now rectified that. Now, with the code you told me to insert (both snippets), I get errors appearing on my page because of the error_reporting. I assume you would like to see them? – Kent Godfrey May 17 '16 at 21:15
  • @KentGodfrey sure. Place them as an additional edit under your question. Again though; you edited without marking it as an edit. you shouldn't do that. People see that type of question with my answer, and say to themselves: *"The guy has it up there, so why the answer?"* and risks in downvoting me. I'm not too crazy about that. – Funk Forty Niner May 17 '16 at 21:17
  • OK I will be sure to change it now w/ and additional edit sentence underneath it. I am sorry – Kent Godfrey May 17 '16 at 21:18
  • Sorted. Its functional now. All of the above helped me correct my work. Thank you very much Fred.I really do appreciate it. Would you like me to do anything to the question before I leave it since my problem is now non-existent. – Kent Godfrey May 17 '16 at 22:09
  • In the end I also had to change my "include" line since that was what was causing the rest of the problems. Here is the snippet of code: include_once dirname(__FILE__).'/db_connect.php'; // PHP >= 5.3 include_once __DIR__.'/db_connect.php'; – Kent Godfrey May 17 '16 at 22:11
  • @KentGodfrey You're welcome and glad to hear it has been resolved. You can leave the question the way it is which is fine. I noticed the *"mixing up the table and column name"* which is what I had thought you might have done and had anticipated for that as shown in my answer at the bottom. You could say my *Spidey sense tingled* lol. Cheers! – Funk Forty Niner May 17 '16 at 23:01
  • Yes Fred, I think you may have bumped into this a few times yourself back in the day of being a "newb". Thanks again! – Kent Godfrey May 17 '16 at 23:24
  • @KentGodfrey We've all went through those (anyone who hasn't, did not learn anything *lol*) and you're quite welcome. – Funk Forty Niner May 17 '16 at 23:28
  • I suggest you also mention the wrong include statement, and point him to the troubleshooting guideline for this : http://stackoverflow.com/questions/36577020/failed-to-open-stream-no-such-file-or-directory – Vic Seedoubleyew May 19 '16 at 19:34
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){
Hossein
  • 1,301
  • 1
  • 12
  • 23
  • Hmm, when I use this if statement it makes my login form always return a white page. Thanks for the input and your time! – Kent Godfrey May 17 '16 at 19:47
  • your welcome , i forget one ")" in if statement. i fixed it. ;) – Hossein May 17 '16 at 19:52
  • 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. – Kent Godfrey May 17 '16 at 21:08