我的配置文件包含一个连接到我服务器上的数据库的函数,这里是代码
配置文件
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', '');
function communicate($dbname){
try {
$dbh = new PDO('mysql:host=serverip;dbname='.$dbname.'', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
}
?>
其他页面做一些事情
require('dbs/connfile.php');
if (isset($_GET['id'])) {
$accountname = 'dbname';
communicate($accountname);
$query = "SELECT * FROM datatbl";
$result= $dbh->prepare($query);
$result->execute();
while ($row = $result->fetch()) {
$cmail = $row['email'];
}
}
我得到了错误,说
注意:未定义的变量:/home/moudlepath/page.php中的dbh
那是因为$dbh
不是全局的,我如何在其中包含的任何页面中使用该连接文件?
答案 0 :(得分:1)
简单的解决方案是:
function communicate($dbname){
try {
$dbh = new PDO('mysql:host=serverip;dbname='.$dbname.'', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
return $dbh; // see this? return your $dbh
}
用法:
$dbh = communicate($accountname);