【发布时间】:2018-11-13 13:28:16
【问题描述】:
我想在我的站点中包含一个用户类,用于用户登录和注册。
我已经完成了所有部分,除了我在课堂上的连接,实际上课堂有它自己的 config.php 但我不能使用它。
我的网站通过正常查询运行,但类配置不允许在课堂外进行查询。
所以我需要在课堂上包含我自己的连接,以便在课堂外用作$stmt=$pdo->prepare 查询。
我尝试了很多变化,并非常努力地让它发挥作用,但每次尝试都失败了。
需要你的帮助。
这是我的 config.php
Class Dbh{
private $servername;
private $username;
private $password;
private $dbname;
private $charset;
protected function Connect(){
$this->servername = "localhost";
$this->username = "localhost";
$this->password = "localhost";
$this->dbname = "localhost";
$this->charset = "UTF-8";
try {
$dsn = "mysql:host=".$this->servername.";dbname=".$this->dbname.";charset=".$this->charset;
$pdo = new PDO($dsn, $this->username, $this->password);
return $pdo;
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
return "Connection Failed!: " . $e->getMessage();
die();
}
}
}
$user = new User();
$user->dbConnect(dsn, username, password);
这是我的课堂连接部分
class User{
/** @var object $pdo Copy of PDO connection */
private $pdo;
/** @var object of the logged in user */
private $user;
/** @var string error msg */
private $msg;
/** @var int number of permitted wrong login attemps */
private $permitedAttemps = 5;
/**
* Connection init function
* @param string $conString DB connection string.
* @param string $user DB user.
* @param string $pass DB password.
*
* @return bool Returns connection success.
*/
public function dbConnect($dsn, $username, $password){
if(session_status() === PHP_SESSION_ACTIVE){
try {
$pdo = new PDO($dsn, $username, $password);
$this->pdo = $pdo;
return true;
}catch(PDOException $e) {
$this->msg = 'Connection did not work out!';
return false;
}
}else{
$this->msg = 'Session did not start.';
return false;
}
}
}
【问题讨论】:
-
您应该查看依赖注入并在
User类的构造函数中注入数据库连接。