I decided that it was somewhat ridiculous, and just created a select_dynamic($array) and put it into my phplibrary.
This function dynamically creates a SELECT form from a SQL database.
Let me know what you think; good, bad or indifferent..
- Code: Select all
function select_dynamic($array) {
if (count($array) < 1) {
return '<option value="">Array was empty.</option>';
}
if ($array['id_field'] != '') {
$WHERE = " WHERE `$array[fieldname]`= '$array[what]' ";
} else {
$WHERE = '';
}
if ($array['orderby'] != '') {
$ORDERBY = "ORDER BY $array[orderby] ";
} else {
$ORDERBY = '';
}
$query = "SELECT ".implode(',',$array['selectfields'])." FROM $array[table] $WHERE $ORDERBY ";
$result = mysql_query($query) or die ("THERE WAS AN ERROR!: ".mysql_error());
if (mysql_num_rows($result) > 0) {
$string = '';
while ($row = mysql_fetch_assoc($result)) {
if ($array['match'] == $row[$array['selectfields']['0']]) {
$string .= '<option value="'.$row[$array['selectfields']['0']].'" selected="true">'.$row[$array['selectfields']['1']].'</option>';
} else {
$string .= '<option value="'.$row[$array['selectfields']['0']].'">'.$row[$array['selectfields']['1']].'</option>';
}
}
} else {
$string = '<option value="">Results not found!</option>';
}
return $string;
}
When calling this script, simply do the following..
- Code: Select all
$array = array( 'table' => 'phone_make',
'id_field' => '',
'orderby' => '',
'selectfields' => array('make_id','make_name')); // change these two fields to your field names
if (isset($_POST['thisnthat'])) {
$array['match'] = $_POST['thisnthat']; // the name of the select field..
} else {
$array['match'] = '';
}
echo '
<form name="somename" method="post" action=".">
<table>
<tr>
<td>Select One:</td>
<td><select name="thisnthat" onChange="javascript:submit(this);">'.select_dynamic($array).'</select></td>
</tr>
</table>
</form>
';

