我正在努力在自己的函数中包含数据库连接。为了简单起见,一切都在一个文件中。我想我需要通过connect函数传递$ db,但我不知道如何将它声明为空对象。我尝试使db成为一个类,然后将db_connect的内容放入__construct并使用$ db = new db;但那也不起作用。
function db_connect(){
try {
$db = new PDO('mysql:host=xxx.xxx.com;dbname=xxx;charset=utf8', 'xxx', 'xxx');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
function getTeamCount($leagueId){
db_connect();
$teamCount = $db->prepare('SELECT ...................');
$teamCount->execute();
$teamCountResult = $teamCount->fetchAll(PDO::FETCH_ASSOC);
$teamsCounted = $teamCount->rowCount();
......
......
}
答案 0 :(得分:1)
function db_connect(){
try {
$db = new PDO('mysql:host=xxx.xxx.com;dbname=xxx;charset=utf8', 'xxx', 'xxx');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $db; //here!
}
function getTeamCount($leagueId){
$db = db_connect();
...
}