For the state select box example, it might be two separate functions: one to retrieve the states from the DB as an array, and a generic function to display a select element from an array.
db_functions.php:
<?php
/**
* Get states from DB as array
* @return array
*/
function getStateArray()
{
$sql = "SELECT `abbrev`, `name` FROM `state` ORDER BY `name`";
$result = mysql_query($sql);
if(!$result)
{
error_log(mysql_error()."\n$sql");
return false;
}
$arr = array();
while($row = mysql_fetch_assoc($result))
{
$arr[$row['abbrev']] = $row['name'];
}
return $arr;
}
html_functions.php:
<?php
/**
* get <select> HTML for an array of data
* @return string
* @param string $name Select element name & ID
* @param array $data Key: option value, Value: displayed value
* @param string $class Select element class (optional)
*/
function selectFromArray($name, $data, $class=null)
{
$html = sprintf(
"<select name='%s' id='%s'%s>\n",
htmlspecialchars($name, ENT_QUOTES),
htmlspecialchars($name, ENT_QUOTES),
(empty($class)) ? '' : " class='".htmlspecialchars($class,ENT_QUOTES)."'"
);
foreach($data as $key => $value)
{
$html .= sprintf(
"<option value='%s'>%s</option>\n",
htmlspecialchars($key, ENT_QUOTES),
htmlspecialchars($value, ENT_QUOTES)
);
$html .= "</select>\n";
}
return $html;
}
index.php:
<?php
require_once 'db_functions.php';
require_once 'html_functions.php';
?>
<form action='' method='post'>
<fieldset>
<legend>Test</legend>
<label for='state'>Select state:</label>
<?php echo selectFromArray('state', getStateArray(), 'class_foo'); ?>
</fieldset>
</form>
If you are reasonably comfortable with the basics of object-oriented PHP, the next step might be to organize related functions into classes.