저는 최근에 동적 PDO 연결 방법을 사용해 왔습니다. 그러나 다른 클래스를 사용할 때 몇 가지 문제가 발생합니다.다른 클래스에서 생성 된 연결 방법을 사용하면 작동하지 않습니다.
서버 클래스에서 생성 된 메서드를 사용하여 Admin 클래스의 데이터베이스에 연결할 수없는 이유는 무엇입니까?
많은 솔루션을 사용해 보았습니다. 이 하나가 내게 가장 논리적 인 것 같았습니다 ...
모든 클래스에서 연결을 만들 필요가 없도록 어떻게 작동합니까?
class Server
{
private $hostdb = 'blah';
private $namedb = 'blah';
private $userdb = 'blah';
private $passdb = 'blah';
public static $conn;
public $errorMessage = 'If you read this text, contact web administrator and tell him about your problem.';
public function __construct()
{
$this->connect();
}
public function connect()
{
try {
$this->conn = new PDO("mysql:host=$this->hostdb; dbname=$this->namedb", $this->userdb, $this->passdb, array(PDO::ATTR_PERSISTENT => true));
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
그리고 관리 클래스 :
내가 config.req.php 파일에서 두 서버, 사용자 및 관리자 클래스를 인스턴스화 한
class Admin extends User
{
function someFunction($table)
{
try {
$sql = "SELECT * FROM $table";
//I want to change this line so that my connection would work
$result = Server::$conn->query($sql);
while ($row = $result->fetch(PDO::FETCH_NUM)) {
//Do something
}
} catch (PDOException $e) {
//Show when debugging
//echo $e->getMessage();
echo Server::errorMessage;
}
}
}
.
"Server :: $ conn->"를 "static :: $ conn->"으로 변경했을 때 여전히 오류가 발생했습니다.
놀라운 소식입니다. 고마워. :) –