article

Saturday, August 17, 2013

Simple PHP Class Drop Down Menu

Simple PHP Class Drop Down Menu 

Create database table

CREATE TABLE `tblcategories` (
  `id` int(11) NOT NULL,
  `Name` varchar(100) collate latin1_general_ci NOT NULL,
  `pid` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;


//index.php
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'test');

class AjaxDropdown
{
	var $table;
	function AjaxDropdown()
	{		
		mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() );
		mysql_select_db (DB_NAME) OR die ('Could not select the database: ' . mysql_error() );
		$this->table = "tblcategories";
	}
	
	function dbConnect()
	{
		mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);
	}
		
	
	function getArray($id)
	{
		$this->dbConnect();
		$query = "SELECT * FROM $this->table where pid = {$id} ORDER BY id asc";
		$result = mysql_query ($query);
		$arr = array();
		while($row = mysql_fetch_object($result))
		{
			$arr[] = $row;
		}
		mysql_close();		
		return $arr;	
	}
}

$strRet = "";
$obj = new AjaxDropdown();
$arr = $obj->getArray(0);
$strRet .= '<option value="0">--Select--</option>';
foreach ( $arr as $row )
{
	$strRet .= '<option value="'.$row->id.'">'.$row->Name.'</option>';
}
?>
<select name="selCat" class="text">
	<?php echo $strRet; ?>
</select>

Related Post