Page 1 of 1

php function

Posted: Fri Oct 21, 2011 5:26 am
by Lphp
I have three drop down box , each them need to use the following code , how can I have a function to handle this part of logical, then I don't need to repeat the code

Code: Select all

$sql = "SELECT * from student";
                        $db->Select($sql, &$result);

                        while ($nrow = mysql_fetch_array($result)) {
                        if (($nrow['id'] == 1) || ($nrow['id'] == 20) 
do something

}
Thank you

Re: php function

Posted: Fri Oct 21, 2011 2:25 pm
by twinedev
Well for me, it would depend how much data you are handling and what you are doing with it, but from the little info give, something like this:

Code: Select all

function DropDown() {

	static $dbCache = NULL;

	if (is_null($dbCache)) {
		$dbCache = array();
		$sql = "SELECT * from student";
		$db->Select($sql, &$result);
		while ($nrow = mysql_fetch_array($result)) {
			$dbCache[] = $nrow;
		}
	}

	foreach($dbCache as $nrow) {
		if (($nrow['id'] == 1) || ($nrow['id'] == 20) {
			// do something
		}
	}
	
}
I'm used to working with a lot of data and complex joins, so my tendency is that any data that will get called more than once, store it. The first part does that, it creates a static variable, whose value will be held across different calls of the function. If that is null (the first call to the function) then it loads up the data from the database (each additional call it will already have the data, so no need to reload from DB). Then it loops through the data doing what you want.

-Greg

Re: php function

Posted: Sun Oct 23, 2011 8:41 pm
by Lphp
Thank Greg,
that is what I looking for, but how to call the function( all including) in my drop down box??

Re: php function

Posted: Mon Oct 24, 2011 10:48 am
by egg82
echo('<select name="yourdropdown">');
DropDown();
echo('</select>');