【发布时间】:2014-12-01 02:15:06
【问题描述】:
我正在尝试为我的网站制作一个 OOP 登录系统,但在连接到 MS SQL 数据库时遇到了真正的麻烦,所以真的遇到了第一个障碍!
我正在使用 SQLSRV 驱动程序,但不能选择安装 PDO。我收到以下错误,我理解这意味着未建立连接并且 db_connection 变量为空:
第 79 行 C:\xxxx\auth.php 中非对象上的成员函数 set_charset() 的致命错误调用
class Auth
{
/**
* @var string - database connection
*/
private $db_connection = null;
/**
* @var array - collection of error messages
*/
public $errors = array();
/**
* @var array - collection of success / neutral messages
*/
public $messages = array();
public function __construct()
{
// create/read session, absolutely necessary
session_start();
// check the possible login actions:
// if user tried to log out (happen when user clicks logout button)
if (isset($_GET["logout"])) {
$this->doLogout();
}
// login via post data (if user just submitted a login form)
elseif (isset($_POST["auth"])) {
$this->doauthWithPostData();
}
}
// AUTHENTICATE
private function doauthWithPostData()
{
$serverName = "%server%";
$User = "%user%";
$Pass = "%pwd%";
$DB = "%dbname%";
$connectionInfo = array( "Database"=>$DB, "UID"=>$User, "PWD"=>$Pass);
// check login form contents
if (empty($_POST['usr'])) {
$this->errors[] = "Username field was empty.";
} elseif (empty($_POST['usr_pwd'])) {
$this->errors[] = "Password field was empty.";
} elseif (!empty($_POST['usr']) && !empty($_POST['usr_pwd'])) {
// create a database connection, using the constants from db.php (loaded in index.php)
$this->db_connection = sqlsrv_connect( $serverName, $connectionInfo);
//$this->db_connection = new mssql_connect(constant(DB_HOST), constant(DB_USER), constant(DB_PASS));
// change character set to utf8 and check it
if (!$this->db_connection->set_charset("utf8")) {
$this->errors[] = $this->db_connection->error;
}
// if no connection errors (= working database connection)
if (!$this->db_connection->connect_errno) {
// escape the POST stuff
$user_name = $this->db_connection->ms_escape_string($_POST['user_name']);
// database query, get all the info of the selected organisation
$qry = "SELECT USR, PASSWORD
FROM USERS
WHERE USR = '" . $_POST['usr'] . "';";
$result_of_auth_check = $this->db_connection->query($qry);
// if this org exists
if ($result_of_auth_check->num_rows == 1) {
// get result row (as an object)
$result_row = $result_of_auth_check->fetch_object();
// password_verify() function to check if the provided password fits
// the hash of that user's password
if (password_verify($_POST['usr_pwd'], $result_row->user_password_hash)) {
// write user data into PHP SESSION
$_SESSION['user_auth_status'] = $_POST['usr'];
} else {
$this->errors[] = "Wrong password. Try again.";
}
} else {
$this->errors[] = "This user does not exist.";
}
} else {
$this->errors[] = "There was a problem connecting to the database.";
}
}
}
我已经尝试在 OOP 之外以完全相同的方式建立连接,它工作得很好。我不明白出了什么问题!感谢您的帮助,非常感谢!
【问题讨论】: