我正在尝试PDO扩展,并且想知道是否可以将数据库连接的开放存储为可以在需要时调用的函数。我尝试了一些基本的东西,但似乎没有用。可以吗?
示例功能
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();
}
}
答案 0 :(得分:0)
称之为:
$ conn = $ this-&gt; DB();
OR
$ conn = $ className-&gt; DB();