Page 1 of 1

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

#1 codeprada   User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 963
  • View blog
  • Posts: 2,382
  • Joined: 15-February 11

Posted 27 July 2011 - 07:25 AM

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'";

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.

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.

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

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

USE `dom_test`;

	`ranks_name`	VARCHAR(25) UNIQUE NOT NULL 

	('Power User'),

Sample Code: The comments should be able to guide your through the script
P.S. Manipulating XML is not limited to the DOM Object
/*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 = array(

	$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

Is This A Good Question/Topic? 3
  • +

Replies To: Simple Solutions: Populating Select Element Using DOM

#2 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4202
  • View blog
  • Posts: 13,275
  • 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