0

我正在尝试 PDO 扩展,并且想知道是否可以将 DB 连接的打开存储为可以在需要时调用的函数。我尝试了一些基本的东西,但它似乎不起作用。它可以?

示例函数

function DB() {
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$conn) {
    echo "<br />MySQL SERVER CONNECTION ERROR.<br />\n";
}
if($conn) {
    return $conn;
}
}

示例用法

function is_post_id($submitted) {

try {
    $id = $submitted;
    DB();   

    //check to see if there is a post
    //with an id matching the submitted query
    $qPOST= $conn->prepare('SELECT COUNT(*) FROM posts WHERE id = :id');
    $qPOST->execute(array('id' => $id)); 

    //results counted
    $cPOST= (int)$qPOST->fetchColumn();
    if($cPOST > 0) {
        return TRUE;
    }
    else {
        return FALSE;
    }
} catch(PDOException $e) {
    echo $e->getMessage();
}
}
4

1 回答 1

0

称之为:

$conn = $this->DB();

或者

$conn = $className->DB();

于 2012-07-25T12:21:37.663 回答