OOPの使い方を学び始め、ユーザーが存在するかどうかを確認するためのユーザー認証クラスを作成しました。現在$dbh
、PDO接続であるグローバル変数を使用してデータベースに接続しています。このようにグローバル変数を使用することは良い習慣ではないと聞きましたが、どうすれば改善できるかわかりません$dbh
。データベースに接続するときに変数を必要とするメソッドに変数を渡すだけで、なぜこれが考慮されないのでしょうか。いい練習?
これが私が使用しているいくつかのコードです:
呼び出し側プログラムに含まれるデータベースPDO接続:
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=oopforum","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
データベース接続を必要とするクラス:
class Auth{
private $dbh;
function __construct(){
global $dbh;
$this->dbh = $dbh;
}
function validateLogin($username, $password){
// create query (placing inside if statement for error handling)
if($stmt = $this->dbh->prepare("SELECT * FROM oopforumusers WHERE username = ? AND password = ?")){
$stmt->bind_param(1, $username);
$stmt->bind_param(2, $password);
$stmt->execute();
// Check rows returned
$numrows = $stmt->rowCount();
//if there is a match continue
if( $numrows > 0 ){
$stmt->close();
return TRUE;
}else{
$stmt->close();
return FALSE;
}
}else{
die('ERROR: Could not prepare statement');
}
}
function checkLoginStatus(){
if(isset($_SESSION['loggedin'])){
return TRUE;
}else{
return FALSE;
}
}
function logout(){
session_destroy();
session_start();
}
}