Jump to content

Archived

This topic is now archived and is closed to further replies.

MadDawgX

Code Problem (Noob Needs Help)

Recommended Posts

Well, Im kinda new to PHP and MySQL in general, though I do have experience in other languages. Just wondering why the following code won't work.

[code]    $query = "SELECT pass FROM User WHERE user='$user'";
    $res = mysql_query($query) or die("Error Executing Query: ".mysql_error());

    if ($res == $pass) {
        $ans = "1";
    }
    else
    {
    $ans = "2";
    }    [/code]

$user and $pass are both test. And the values in the MySQL database User are (user=test and pass=test)

EDIT: Oh and $ans is returning 2 when it should be 1.

- Thanx

Share this post


Link to post
Share on other sites
[quote author=MadDawgX link=topic=102669.msg407798#msg407798 date=1154492954]
[code]    $query = "SELECT pass FROM User WHERE user='$user'";
    $res = mysql_query($query) or die("Error Executing Query: ".mysql_error());

    if ($res == $pass) {
        $ans = "1";
    }
    else
    {
    $ans = "2";
    }    [/code]

$user and $pass are both test. And the values in the MySQL database User are (user=test and pass=test)

EDIT: Oh and $ans is returning 2 when it should be 1.
[/quote]
$res is actually set to the query string, so it'll never equal the password string, not to mention you aren't setting $pass to anything as far as I can tell so $pass is a null value.  You'd have to do something like the following:

My example assumes this is web based, and the previous page had a username and password field for the user to fill out.
[code]
//Use the posted user field as the query variable for user
$query = "SELECT pass FROM User WHERE user='$_POST[user]'";
$res = mysql_query($query) or die("Error Executing Query: ".mysql_error());
//the while loop goes through any results from the database and puts password in a variable, and the mysql_num_rows test makes sure that there are rows
if(mysql_num_rows > 0) {
  while ($row = mysql_fetch_assoc($res)) {
    $pass = $row['pass'];
  }
} else {
//No results returned from DB
  echo "Incorrect username or password";
  exit();
}
//value of password field on form page is equal to password in database
if ($_POST['pass'] == $pass)
{
    $ans = "1";
}
else
{
    $ans = "2";
}
[/code]
I hope this is helpful!

Jon

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.