-2

我一直在试图找出将我的 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();

}

}

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

4

2 回答 2

4

您正在将程序 mysql_* 函数与 PDO 混合。为什么不设置 PDO 对象并通过 setter 方法/构造函数将其分配给对象?

$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(".."); /* .. */ }
}

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

于 2012-04-29T19:16:27.167 回答
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();
    }
}

} 
于 2012-08-11T00:13:08.053 回答