如何在 class 中多次使用 PDO prepare

How to use PDO prepare more than oncee in a class

class dbConnection {

    function connect(){
        try{
            $this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
            return $this->db_conn;
        } catch(PDOException $e) {
            return $e->getMessage();
        }
    }
}

class student{
    public $link;

    public function __construct(){
        $db_connection = new dbConnection();
        $this->link = $db_connection->connect();
        return $this->link;
    }

    public function checkLogin($username,$password){
        $query = $this->link->prepare("SELECT * FROM studentprofiles where UserName = :uname AND LogPassword = (select md5(:upassword));");
        $query->execute(array(':uname' => $username, ':upassword' => $password));
        $count = $query->rowCount();
        if($count === 1){
            $this->setSession($username);
        }
        return $count;
        $query = null;
    }

    public static function display(){
        $query = $this->link->prepare("SELECT ForeName, Surname FROM studentprofiles where UserName = :uname;"); //getting error here: Fatal error: Using $this when not in object context
        $query->execute(array(':uname' => self::getSession()));
        while($row = $query->fetch(PDO::FETCH_ASSOC)) {
            printf (" <span id='WelcomeName'> Welcome: %s %s\n </span>",$row[0],$row[1]);
        }
        $query = null;
    }
}

再次使用 $this 准备另一个 select 语句时出错,如何在同一个 class 中再次将它用于另一个函数?谢谢

感谢任何帮助,真的卡在这个问题上了

你好,你可以检查你的代码,我更喜欢登录以评估连接示例

 $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  

在你的函数中你做了一些这样的事情

function connect(){
        try{
            $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
            return $conn;
        } catch(PDOException $e) {
            return $e->getMessage();
        }
    }

在一个完整的示例中:

$id = 5;
try {
    $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    

    $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

请尝试并祝你好运