vic vance Posted April 19, 2012 Share Posted April 19, 2012 Hey, I am coding this forum and the following PDO prepare query calls the topic details. The prepare query works perfectly well, however when I add it into a function within another class and then call it, the script does not seem to work. I get errors like the following: Fatal error: Call to a member function fetch() on a non-object in C:\wamp\www\new\sources\forum\new.php on line 117 The prepare query fails to excute, this is because I do not know how to add it into a function. This is what I tried: class FUNC { function userDetails($table, $column, $cVaulue, $oBy, $ASDSC) { global $dbh; $sth = $dbh->prepare('SELECT * FROM `'.$table.'` WHERE `'.$column.'` = '.$cVaulue.' ORDER BY `'.$oBy.'` '.$ASDSC.''); $sth->bindParam(':id', $id, PDO::PARAM_INT); $sth->execute(); } } The FUNC class is called as the $load variable, and in my forum class I have decalred it in my global so the variable can be passed: $id = $forum_data['id']; $load->userDetails('db_topics', 't_forum_id', ':id', 't_whenlast', 'DESC'); $coll=$sth->fetch(PDO::FETCH_ASSOC); $this->html->RightForum($coll); The code is very silly, but the fact is I did not know how to do this.. Please help me put this query into a function because I need to make use of it in many other parts of the forum and I don't want to constantly declare this query. Quote Link to comment https://forums.phpfreaks.com/topic/261236-pdo-prepare-query-into-a-function/ Share on other sites More sharing options...
trq Posted April 19, 2012 Share Posted April 19, 2012 Functions and classes are meant to be protected from global variables. Using them the way you are attempting to completely breaks the entire point of using them in the first place. If your FUNC class requires a database connection, pass it one via it's constructor. I can tell however by the name of your class FUNC, that you really shouldn't be using a class in this case anyway. Quote Link to comment https://forums.phpfreaks.com/topic/261236-pdo-prepare-query-into-a-function/#findComment-1338704 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.