views:

66

answers:

2

I'm trying to make an OO Login system for a project I'm working on, and am having trouble with inserting variables into the query strings. In the code below, if I replace "$TBL_NAME" with the actual table name it works. Why isn't $TBL_NAME translating to the value of $TBL_NAME?

class UserDB {

  private $TBL_NAME = "users";

  public static function CheckLogin($username, $password) {

    Database::Connect();

    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);

    $sql="SELECT uid FROM $TBL_NAME WHERE username='$username' AND password='$password' ";
    $result =mysql_query($sql);
    $count=mysql_num_rows($result);
    if ($count==1)
      return true;
    else
      return false;
  }

The Query is returning false.

A: 

Declare $TBL_NAME as private static, not just private, and use self::$TBL_NAME. Not sure of the syntax within a string — I’d just use the concatenation operator instead (i.e., "SELECT uid FROM " . self::$TBL_NAME . " WHERE …"

Mo
Also, you should only use `stripslashes` if `get_magic_quotes_gpc()` is `true`, and the value came from `$_GET`, `$_POST`, `$_COOKIE` or `$_REQUEST` — doing this in your database class is horrible leaky abstraction.
Mo
Note also that `mysql_num_rows()` will emit a warning if `$result` is not a valid result resource. Also, you should never be storing passwords in cleartext! Retrieve the row, and use the stored password as the salt in hashing the supplied one (compare the result of that hashing operation with the stored password, and return `true` if they match — see `crypt()`)
Mo
+2  A: 

A little more on the reason(s) your code didn't work: Php's OO syntax requires you to use the qualifier on instance and class variables. In other words, you can't leave out 'this' like in other languages.

If your CheckLogin method wasn't static, the variable $TBL_NAME still wouldn't be set inside the function. To get the instance variable, you'd have to use $this->TBL_NAME.

Since your method is static, it has access to static variables but not instance variables, so you have to make the variable static. Once you do that, you can access it with self::, as in Mo's answer.

grossvogel
awesome, I appreciate the further info. Looks like I've got some work to do in my other classes as well then. If I do omit the $this-> for instance variables, will it just create new variables in the current scope?
jon
Yep.. inner function variables
Hermet