TurnedTurquoise
TurnedTurquoise

Reputation: 37

Having an issue confirming data using mysql with my database

Okay I have been using mysql for use with my website however it has not been going well with some of the syntax. I've read up on it but I fell like I'm still doing it wrong... In the picture below, I have defined database variables and then tried to log into my database containing the columns of "ID" "Username" and "Password". I then define the username and password input, from my form, in the php and asked the database to compare... am I missing something? I feel like it's not comparing the data from the form with the data in the database. It works even if I type the password wrong..

//Name of File: LoginCheck.php <--Called with the Login.php (which has a form on it) 
//posts information to LoginCheck.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'blah');
define('DB_PASS', 'blah');
define('DB_NAME', 'Profiles');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if(!$con){
    die('Could not connect. ' . '<br/>' . 'Error: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $con);
if(!$db_selected){
    die('Could not select database: ' . DB_NAME . '<br/>' . 'Error: ' . mysql_error());
}
//defines login variables from the form.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$login =  mysql_query("SELECT * FROM Users WHERE Username = '$username' AND Password = '$password'", $con);
if(!$login){
    echo 'Error: ' . mysql_error();
    echo "Didn't log in. Not matching database intel.";
}else{
echo "Logged in matching database intel.";
}
mysql_close($con);
?>

Upvotes: 0

Views: 42

Answers (2)

John Conde
John Conde

Reputation: 219824

mysql_query() just returns a resource. You can then use that resource to get that data or more information about the query.

You can use mysql_num_rows() to see if your query was successful:

if(!mysql_num_rows($login)){

FYI, you should not be storing passwords in plain text. That is a huge security no-no.

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Upvotes: 3

Barmar
Barmar

Reputation: 781068

It should be:

$login =  mysql_query("SELECT * FROM Users WHERE Username = '$username' AND Password = '$password'", $con);
if(!$login){
    echo 'Error: ' . mysql_error();
} elseif (mysql_num_rows($login) == 0) {
    echo "Didn't log in. Not matching database intel.";
}else{
    echo "Logged in matching database intel.";
}

Not finding a match is not the same as an error.

Upvotes: 2

Related Questions