PHP脱离类pdo连接失败

时间:2017-07-09 11:13:47

标签: php class pdo

我不能在课外进行PDO连接。浏览器提供500错误。我想在课外编写PDO代码。我正在做全球变革,但事实并非如此。

try { 
    $pas = new PDO('mysql:host=localhost; dbname=tets', 'root', '123');   
    $pas->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); 
    $pas->exec("SET CHARACTER SET utf8");  //  return all sql requests as UTF-8   
} catch (Exception $e) { 
    echo $e->getMessage(); 
} 
/** 
 User Avatar Check 
**/ 
class Usercheck 
{ 
    public $sql , $paso; 


    public function __construct() 
    { 
        global $pas; 
        $this->paso =& $pas; 
    } 

    public function smf_members($whatid) 
    { 

        $this->sql = $this->paso->query("SELECT * FROM smf_members WHERE id_member = $whatid");         
    } 

    public function fetchcheck(){ 
        if ($this->sql) { 
            return $this->sql->fetch(PDO::FETCH_BOTH); 
        } 
    } 
} 

$memberuser = new Usercheck(); 
$memberuser->smf_members('1');

1 个答案:

答案 0 :(得分:0)

使用$ global不是一个好习惯。有很多解决方案可以实现您想要做的事情,这是我的方法。

1)创建一个Connection Class来处理PDO连接。

use PDO;
/**
* PDO Connection Classes
* Used by Database wrapper class to ensure that there is only one connection
*/
class Connection
{
    private $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME. ';charset=' . DB_CHARSET;
    private $conn;
    private $error;

    public function __construct()
    {
        try
        {
            $this->conn = new PDO($this->dsn, DB_USER, DB_PASSWORD);
        }
        catch(PDOException $e)
        {
            $this->error = $e->getMessage();
        }
    }

    public function getConnection()
    {
        return $this->conn;
    }

}

2)通过包装类__construct()建立PDO连接,__ construct()也确保只实例化一个PDO连接。

use PDO;
class UserCheck
{
    private $conn;
    private $db;

    public function __construct()
    {
        if (!$this->db) {
            $conn = new Connection();
            $this->db = $conn->getConnection();
        }
    }
}

我强烈建议您阅读此PDO tutorial,了解如何使用PDO以及许多最佳做法提示。