Board index   FAQ   Search  
Register  Login
Board index PHP Your Scripts

Dynamic Select Generator

This is where you share YOUR scripts with others

Moderators: macek, egami, gesf

Dynamic Select Generator

Postby egami » Thu Jun 16, 2011 10:10 am

After many, many times of coding in SQL generated select fields, and having 30 or so of them on a form..
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>
'
;
 
User avatar
egami
php-forum GURU
php-forum GURU
 
Posts: 2196
Joined: Wed Oct 06, 2010 11:19 am
Location: Happy Valley, UT

Return to Your Scripts

Who is online

Users browsing this forum: No registered users and 2 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.