Jump to content

PDO prepare query into a function?


vic vance

Recommended Posts

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.

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.