gpt4 book ai didi

PHP OOP 和 PDO

转载 作者:行者123 更新时间:2023-12-01 00:27:08 25 4
gpt4 key购买 nike

我第一次真正尝试广泛使用 PHP OOP 和 PDO。我终于让脚本工作了,但正如你注意到的那样,为了做到这一点,我不得不将 PDO 连接移动到登录功能中 - 最初它只是在 __construct() 中。 .我不想打开一个新的 PDO 连接,这很草率。如何在整个类(class)中保持相同的连接?

 <?php
class user{

public $id;
public $name;
public $email;
private $password;

public function __construct() {
$DBH = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

public function login($email,$password,$type){

$DBH = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$password_hash = sha1($password);
try{
if ($type != "actives") {
throw new Exception("Type Handling Error");
}
$STH = $DBH->query("SELECT id, email, password FROM $type WHERE email='$email' AND password='$password_hash'");
$STH->setFetchMode(PDO::FETCH_ASSOC);
$row_count = $STH->rowCount();
$row = $STH->fetch();

if($row_count == 1){
session_start();
session_regenerate_id();
$_SESSION['id'] == $row[id];
return true;
}
else{
return false;
}
}
catch (Exception $e) {
echo $e->getMessage();
}

}

public function loggout(){
session_destroy();
setcookie(session_name(), session_id(), 1, '/');
}

最佳答案

使数据库处理类中的私有(private)成员:

class user
{
public $id;
public $name;
public $email;
private $password;
private $dbh;

public function __construct(PDO $dbh)
{
$this->dbh = $dbh;
}

public function login($email, $password, $type)
{
$dbh = $this->dbh;
...
}

用法:
$pdo = new PDO("mysql:host=HOST;dbname=DB", "USER", "PASS");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$user = new User($pdo);

关于PHP OOP 和 PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9048274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com