我是非常新的PHP,所以我有一个非常棘手的问题。我尝试编写能帮助我使用DB的类。代码在这里:
<?php
class DbHelper{
private $databaseURL;
private $databaseUName;
private $databasePWord;
private $databaseName;
private $nameOfDbWithWorkers;
private $connection;
function __construct($dbURL, $dbUserName, $dbPword, $dbName, $nameOfDbWithWorkers){
$this->databaseURL = $dbURL;
$this->databaseUName = $dbUserName;
$this->databasePWord = $dbPword;
$this->databaseName = $dbName;
$this->nameOfDbWithWorkers = $nameOfDbWithWorkers;
}
function setConnectionToDb(){
$connection = mysql_connect($this->databaseURL,$this->databaseUName,$this->databasePWord) OR DIE("can't connect to DB");
mysql_select_db($this->databaseName, $connection)or die ("Error while connecting to database");
}
function getUser($login, $pass){
$query = "SELECT type FROM $this->nameOfDbWithWorkers WHERE login = '$login' and password = '$pass';";
$queryResult = $this->getDataFromDbByQuery($query);
echo $queryResult;
if ((mysql_affected_rows($connection) == 1)){
$meta = mysql_fetch_assoc($queryResult);
if ($meta['type']=='admin'){
return 'admin';
}
if ($meta['type']=='user'){
return 'user';
}
else{
return 'nomatch';
}
}
else{
return 'nomatch';
}
}
function getDataFromDbByQuery($query){
$this->setConnectionToDb();
$result = mysql_query($query);
mysql_close($connection);
return $result;
}
}
?>
我调用getUser
方法,但在$connection = null
方法和getUser
中遇到问题 - getDataFromDbByQuery
。为什么这样?
答案 0 :(得分:5)
因为一个简单的变量总是本地的(除了你使用global
使它变得全局,但是不习惯这个;))。您可能正在寻找的是一处房产。您已经定义了private $connection
,但只是在方法中使用$connection
而不使用它,但是您尝试访问未定义的局部变量
function setConnectionToDb(){
$this->connection = mysql_connect($this->databaseURL,$this->databaseUName,$this->databasePWord) OR DIE("can't connect to DB");
mysql_select_db($this->databaseName, $this->connection)or die ("Error while connecting to database");
}
//..
function getUser($login, $pass){
$query = "SELECT type FROM $this->nameOfDbWithWorkers WHERE login = '$login' and password = '$pass';";
$queryResult = $this->getDataFromDbByQuery($query);
echo $queryResult;
if ((mysql_affected_rows($this->connection) == 1)){
// ...
}
}
等等。只需将$connection
替换为$this->connection
。
答案 1 :(得分:4)
尝试将$connection
替换为$this->connection
。
$connection
指的是本地范围的变量 - 即在您当前所在的函数之外不可用的变量。$this->connection
指的是成员变量您使用private $connection
定义的类。