How do you make a function to query?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ChrisF79
Forum Commoner
Posts: 26
Joined: Tue Apr 01, 2008 8:26 pm

How do you make a function to query?

Post by ChrisF79 »

I want to make a simple function that I can call on to query my database. I pass the "where" part of the query to it and in the code below, my $q variable is correct. However, what should I then do to be able to use the data? I'm so confused at how to do something I'm sure is extremely easy. Any help is greatly appreciated!

Code: Select all

function getListings($where_clause)
{
	$q = "SELECT * FROM `listings` $where_clause";
	$result = mysql_query($q,$dbh);
	foreach (mysql_fetch_array($result) as $row) {
		$listingdata[] = $row;
	}
	return $listingdata;
}
PradeepKr
Forum Newbie
Posts: 14
Joined: Wed Aug 11, 2010 8:29 am

Re: How do you make a function to query?

Post by PradeepKr »

Pass the DB connection link ($dbh) also to the function as param

Code: Select all

function getListings($where_clause,$dbh)
{
        $q = "SELECT * FROM `listings` $where_clause";
        $result = mysql_query($q,$dbh) or die("Error in executing sql".mysql_error() );
        $listingdata = array();
        while($row = mysql_fetch_array($result)) {
                $listingdata[] = $row;
        }
        return $listingdata;
}
Post Reply