在类中包含PDO数据库连接

时间:2012-04-29 19:09:03

标签: php mysql pdo

我一直在努力找出在我的课程中包含PDO数据库连接的最佳方法。这是我到目前为止的代码,不起作用。

class Delete {

private $connection;
    function __construct() {
        $this->open_connection();
    }
    public function open_connection() {
        $this->connection = mysql_connect(localhost, 1, 1);
        if (!$this->connection) {
            die("Database connection failed: " . mysql_error());
        } else {
            $db_select = mysql_select_db(1, $this->connection);
            if (!$db_select) {
                die("Database selection failed: " . mysql_error());
            }
        }
    }

public function delete_file($deletelink) {

$dbh = $this->connection;



$sth = $dbh->prepare("SELECT hash FROM files WHERE delete_link = :delete_link");
//PARAM_INT for int, PARAM_STR for string, PARAM_BOOL for bool
$sth->bindParam(':delete_link', $deletedlink, PDO::PARAM_STR);
$sth->execute();
$countrows = $sth->rowCount();
 if ($countrows == 0) {
return false;   
 } else {



$sth = $dbh->prepare("SELECT filename, hash, ext FROM files WHERE delete_link = :delete_link");
//PARAM_INT for int, PARAM_STR for string, PARAM_BOOL for bool
$sth->bindParam(':delete_link', $deletedlink, PDO::PARAM_STR);
$sth->execute();

}

}

如果有人有更好的方法,请分享=)谢谢你们!

2 个答案:

答案 0 :(得分:4)

您正在将程序性mysql_ *函数与PDO混合使用。为什么不设置PDO对象并通过setter-method / constructor将其分配给对象?

$pdo = new PDO($dsn);
$delete = new Delete($pdo);
$delete->deleteFile($filename);

// ..
class Delete {
  protected $_pdo;
  public function __construct(PDO $pdo) { $this->_pdo = $pdo; }
  public function deleteFile($filename) { $this->_pdo->query(".."); /* .. */ }
}

请考虑更改您的班级名称,它太常见了(删除什么?在哪里?怎么办?)

答案 1 :(得分:0)

我使用一个非常简单的类,使用静态连接:

源: http://simple_pdo_implementation.onlinephpfunctions.com

<?php
class sql
{
public static $db = false;
private $database_host = '127.0.0.1';
private $database_user = 'username';
private $database_pass = 'verySecretPassWord';
private $database_db = 'database';

function __construct()
{
    if (self::$db === false) {
        $this->connect();
    }
    return self::$db;
}

private function connect()
{
    $dsn = $this->database_type . ":dbname=" . $this->database_db . ";host=" . $this->database_host;
    try {
        self::$db = new PDO($dsn, $this->database_user, $this->database_pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
        self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        //Comment this out on a production environment
        //print_r($e->errorInfo);
        //echo 'Connection failed: ' . $e->getMessage();
    }
}

}