Page 1 of 1

Simple Solutions: Populating Select Element Using DOM Rate Topic: -----

#1 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 947
  • View blog
  • Posts: 2,355
  • Joined: 15-February 11

Posted 27 July 2011 - 07:25 AM

Scenario
Many times you'll want to populate a SELECT element or a drop down box with the results returned from my database query and set the default value as well. It's all fine and dandy until we've reached the 'set the default option' part of our code. 99.9% of the time I've seen something similar to this
echo "<select name='select'>
while($row = mysql_fetch_assoc($results)) //Doesn't have to be MySQL
{
	echo "<option value='{$row['value']}'>{$row['whatever']}</option>";
}
echo "</select>";


If you'd want to select a value as the default value then you'll have to modify it to something like this
echo "<option value='{$row['value']}'" 
if($row['value'] == 'a value')
	echo "selected='selected'";
echo">{$row['whatever']}</option>";



It may work but it gets very confusing very quickly and technically breaks the principle of code separation. In this tutorial I will attempt to guide you through a must cleaner design while adhering to principles of code separation.

Solution
PHP has a few objects to manipulate XML. I'll talk about my personal favourite, DOM.

So basically the elements we're working with are SELECT and OPTION. SELECT will be the parent of OPTION or OPTION will be the child of SELECT. The attributes we may want to add for our SELECT are NAME and ID. Those for our OPTION are VALUE.

Our structure in visual form. Yep a normal SELECT element nothing special. You may want to make a diagram at times when you're going to make more complex trees.
<SELECT -ID -NAME>
	<OPTION -VALUE></OPTION>
</SELECT>



Before we start let's make our sample database and table so we can see the code in action.

MySQL
CREATE DATABASE IF NOT EXISTS `dom_test` CHARACTER SET latin1 COLLATE latin1_swedish_ci;

USE `dom_test`;

CREATE TABLE IF NOT EXISTS `ranks`
(
	`ranks_id` 	INTEGER PRIMARY KEY AUTO_INCREMENT,
	`ranks_name`	VARCHAR(25) UNIQUE NOT NULL 
)ENGINE = INNODB;



INSERT INTO 
	`ranks`(
		`ranks_NAME`
	)
VALUES
	('Administrator'),
	('Power User'),
	('User'),
	('Guest');



Sample Code: The comments should be able to guide your through the script
P.S. Manipulating XML is not limited to the DOM Object
<?php
/*Constants to connect to our database*/
/*Fill these constants with the necessary values*/
define('HOST', 'mysql:host=yourhosthere;dbname=dom_test');
define('USER', '');
define('PASS', '');
/************************************************/

/*PDO OPTIONS*/
$pdo_options = array(
		PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
		PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_LAZY /*Why not?*/
);

try
{			
	$pdo = new PDO(HOST, USER, PASS, $pdo_options);
	
	/*
	 *Just to be neat we'll order the Rank Names
	 */
	$ps = $pdo->query('SELECT * FROM `ranks` ORDER BY `ranks_name` ASC;');
	
	$dom = new DOMDocument();
	/*
	 *appendChild returns the node that was added
	 *we'll need to modify it later
	 */
	$select = $dom->appendChild(new DOMElement('select'));
	
	/*
	 *Here we'll set the name attribute to ranks
	 */ 
	$select->setAttribute('name', 'ranks');
	
	
	while($obj = $ps->fetch())
	{
		/*
		 *We get our options so we can modify them later
		 *Notice we append them to the $select element because they are apart of the select
		 */
		$option = $select->appendChild(new DOMElement('option'));
		$option->appendChild($dom->createTextNode($obj->ranks_name)); /*Text node is what the user will see*/
		$option->setAttribute('value', $obj->ranks_id); 
		
		/*
		 *Let's set the 2nd item
		 */
		if($obj->ranks_id == 2)
			$option->setAttribute('selected', 'selected');
	}
	echo $dom->saveHTML(); /*Output our HTML*/
}
catch(PDOException $pdo_exception)
{
	echo 'PDO Exception caught : ' . $pdo_exception->getMessage();
}
catch(Exception $exception)
{
	echo 'Exception caught : ' . $exception->getMessage();
}
?>


Useful Links
Introduction to PDO - Dormilich
Code Separation - CTphpnwb
DOM

Is This A Good Question/Topic? 2
  • +

Replies To: Simple Solutions: Populating Select Element Using DOM

#2 Dormilich  Icon User is online

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,251
  • Joined: 08-June 10

Posted 16 January 2012 - 05:05 AM

note to Sample Code line #43:
in PHP it is possible to create a DOMElement with it's containing text at once:
$option = $select->appendChild($dom->createElement('option', $obj->ranks_name));
$option->setAttribute('value', $obj->ranks_id);

though make sure that the text does not contain invalid HTML characters (noteably <). either use htmlentities() or use the mentioned ->createTextNode() method within the original approach.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1