Pages

Tuesday, July 29, 2008

Generating select box from class.(PHP5)

How many times we need to write selectbox code 0n our page.
Lets say in my website there are 10 pages where i need select box for country.
so writing same code on all of 10 page is very iritating job.
the best way is to write either a function or class for that. with object-oriented concept of php 5 we can tremendously reduce that tedious code on every page.

just make a class file for that contains functions for every selectbox.

like if u want a country selectbox then

make a class file , call that class on ur page and aha!!!
you got the box. no need to write time and again same code on every page.


just type or copy this code for class file

class Select_Option_Class {

public function buildCountrySelect($country_id = false, $selectName = 'country') {
$this->countrySelect = '';
$sql = 'SELECT * FROM country ORDER BY printable_name';
$result = mysql_query($sql);
if (!$result || !mysql_num_rows($result)) return false;

while ($row = mysql_fetch_array($result)) {
$this->countrySelect .= ''."\n"; }
$this->countrySelect = ''."\n";
return $this->countrySelect;
}

}

include following line in ur config file so that you don't need to call it on every page

require_once('admin/class/Select_Option_Class.php');
$selectOption = new Select_Option_Class();

now finally use this line on ur page to call the function

echo $selectOption->buildFrontCountrySelect($country);


thats it.

here u can find that instead of writing selectbox code on every page. u are done with just a single line code.

enjoy coding!!!!!!!!!!!!!!!!!



1 comment:

Anonymous said...

realy good article.. Thanks a lot,
it helped me out solving a drop down box problem. it is easier to use objects. keep on this good work, thanks again.