php function

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
Lphp
Forum Commoner
Posts: 74
Joined: Sun Jun 26, 2011 9:56 pm

php function

Post 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
Last edited by Benjamin on Fri Oct 21, 2011 7:23 am, edited 1 time in total.
Reason: Added [syntax=php|sql|css|javascript] and/or [text] tags.
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: php function

Post 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
Lphp
Forum Commoner
Posts: 74
Joined: Sun Jun 26, 2011 9:56 pm

Re: php function

Post by Lphp »

Thank Greg,
that is what I looking for, but how to call the function( all including) in my drop down box??
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: php function

Post by egg82 »

echo('<select name="yourdropdown">');
DropDown();
echo('</select>');
Post Reply