I am struggling immensely to contain a db connection within its own function. To keep it simple everything is in one file. I think I need to pass $db through the connect function, but I don't know how to declare it as an empty object. I tried making db a class, then placing the contents of db_connect into a __construct and using $db = new db; but that didn't work either.
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();
......
......
}
1 Answer 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();
...
}
answered Jun 5, 2014 at 3:03
user2990252
1811 gold badge1 silver badge9 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-php
function getTeamCount()shouldn't have to worry about making db connections. At minimum, you could just havegetTeamCount()create the SQL statement and send that to another (new) function that 1) connects to the db, 2) executes the query, and 3) returns either the resulting object or an array with a single row of data. That's what I'd do, at least (aside from using maybe an ORM)