Reputation: 79
i wrote a simple code for login page using PHP and Mysql but it always return the false value in the condition (if). whats wrong? this is my code :
..... (successfully connected to database)
$User = $_POST['username'];
$Pass = md5($_POST['password']);
$sql = "SELECT ID FROM users WHERE Username=$User and Password=$Pass";
$result = $conn->query($sql);
$count = mysql_num_rows($result);
if($count == 1) {
$_SESSION['username'] = $User;
header( 'Location: panel.php' ) ;
}
else {
header( 'Location: login.php?status=1' ) ;
}
}
Upvotes: 1
Views: 895
Reputation: 74232
I am under the impression that you are using an Object oriented style to connect with when using mysqli_
functions as per $result = $conn->query($sql);
then using a mysql_
function mysql_num_rows()
after.
mysql_
does not support this method.Example of an object oriented style of connection as per the manual
http://php.net/manual/en/mysqli.query.php:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
Those different APIs do not intermix with each other.
Sidenote: If this isn't the case, then you will need to show us what API you are using to connect to your database with.
Plus, the fact that it's already been established in comments that you need to quote your variables in the WHERE
clause.
Therefore you need to change
$count = mysql_num_rows($result);
to
$count = mysqli_num_rows($result);
or
$count = $result->num_rows;
as per http://php.net/manual/en/mysqli-result.num-rows.php using an Object oriented style.
and the WHERE
clause to
WHERE Username='$User' and Password='$Pass'
I noticed you are using MD5. If this is the case, it is highly discouraged, since it is old and considered "broken".
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash()
function. For PHP < 5.5 use the password_hash() compatibility pack
.
Plus, in regards to SQL injection which is something your code is subject to, use mysqli
with prepared statements, or PDO with prepared statements, they're much safer.
Upvotes: 1
Reputation: 514
The proper way to get $count would be
$count = $result->rowCount();
I'll add more to this answer if there are further problems.
Upvotes: 0
Reputation: 4629
@Fred -ii- is right.
$sql = "SELECT ID FROM users WHERE Username=$User and Password=$Pass";
will result in this query being sent to the database:
SELECT ID FROM users WHERE Username=user and Password=password
You need to quote the user
and password
, otherwise MySQL will not know they're strings:
$sql = "SELECT ID FROM users WHERE Username='$User' and Password='$Pass'";
Upvotes: 0