Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Gard Mikael Fjeldavli
Gard Mikael Fjeldavli
19,416 Points

Fetching method from other file

I have a issue with PHP that I just cant figure out. I have a method in a file called dbmethods.php, that I am trying to invoke from another file (lets call it index.php). This is the method.

function getAllDevicesFromUser($userID){
  $query = $db->prepare("SELECT * FROM devices WHERE UserID = " . $userID);
  $query->execute();
  $devices = $query->fetchAll();
  return $devices;
}

So the first thing you might question is the $db variable. This is again included from another file called database.php. Now the weird thing is that this $db variable seems to work in other cases (I use it frequently), but not in this case. I have tried putting a echo statement before the first statement in the method and it echoes it out, but not if I try after the first statement.

So it is this line that creates the problem in my opinion.

 $query = $db->prepare("SELECT * FROM devices WHERE UserID = " . $userID);

Now, the string could cause the problem, but I have tested it and it is a valid string. So I think it has to do with the $db variable, but I have no idea what that might be.

Anyone want to has any idea?

2 Answers

Martin Aasen
Martin Aasen
9,067 Points

Be sure that you put the require(file) inside the method to make the variables available to the function.

Just spent a few hours myself on a similare problem before figuring this out.

Hope this helps!

Gard Mikael Fjeldavli
Gard Mikael Fjeldavli
19,416 Points

awesome. it works! does that mean I have to include it in all my methods? this seems a bit redundant...