Page 1 of 1

How do you make a function to query?

Posted: Tue Sep 14, 2010 8:59 pm
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;
}

Re: How do you make a function to query?

Posted: Wed Sep 15, 2010 1:16 am
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;
}