[英]PHP mySQL query's and PHP Variables
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. 我正在尝试为我正在研究的项目制作OO登录系统,但是在将变量插入查询字符串时遇到了麻烦。 In the code below, if I replace "$TBL_NAME" with the actual table name it works.
在下面的代码中,如果我将“ $ TBL_NAME”替换为实际的表名,它将起作用。 Why isn't $TBL_NAME translating to the value of $TBL_NAME?
为什么$ TBL_NAME不能转换为$ 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 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. 关于代码无法正常工作的原因:Php的OO语法要求您在实例变量和类变量上使用限定符。 In other words, you can't leave out 'this' like in other languages.
换句话说,您不能像其他语言一样遗漏“ this”。
If your CheckLogin method wasn't static, the variable $TBL_NAME
still wouldn't be set inside the function. 如果您的CheckLogin方法不是静态的,则变量
$TBL_NAME
仍不会在函数内设置。 To get the instance variable, you'd have to use $this->TBL_NAME
. 要获取实例变量,您必须使用
$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. 完成此操作后,您可以使用
self::
来访问它,就像Mo的答案一样。
Declare $TBL_NAME
as private static
, not just private
, and use self::$TBL_NAME
. 将
$TBL_NAME
声明为private static
$TBL_NAME
,而不仅仅是private
,并使用self::$TBL_NAME
。 Not sure of the syntax within a string — I'd just use the concatenation operator instead (ie, "SELECT uid FROM " . self::$TBL_NAME . " WHERE …"
不确定字符串中的语法-我只是使用串联运算符(例如,
"SELECT uid FROM " . self::$TBL_NAME . " WHERE …"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.