0

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();
......
......
}
asked Jun 5, 2014 at 2:57
1
  • function getTeamCount() shouldn't have to worry about making db connections. At minimum, you could just have getTeamCount() 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) Commented Jun 5, 2014 at 3:02

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.