p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: Re: Nick other option


Message #1 by "Gellings, C.O." <gellingsco@p...> on Mon, 20 May 2002 21:56:04 +0200
Nick why not make a field type enum en preset those values you only need to
read the field type from the table to obtain the same. This is part of the
code I use:

	$namesconnect = mysql_connect($DBServer, $DBLogin, $DBPwd);
	mysql_select_db($DBName, $namesconnect);
	$strSQL = "SHOW FIELDS FROM " . $tablename;
	$fields_rst = mysql_query($strSQL);
	$fields_cnt = mysql_num_rows($fields_rst);
	if(mysql_errno() != 0) echo mysql_errno()." = " .mysql_error();

	while($rows = mysql_fetch_array($fields_rst))
		{

		?><tr>
		<td width="150">
		<?
//	Show field description
		$i++;
		echo $GLOBALS["lblname"][$i]["naam"];
//	Get enumeration values for radiobuttons if applicable
		if(eregi('^(set|enum)\((.+)\)$', $rows['Type'], $Tmp))
		{
			$Tmp[2] = substr(ereg_replace('\([^,])\'\'', '', ',' .$Tmp[2]), 1);
			$val = str_replace('\'', '', $Tmp[2]);
			$val = explode(',',$val);
			$type = $Tmp[1] . ' ' . str_replace(',', ', ', $Tmp[2]);
		}
//	Now get field type to determine type of input field
		$type = substr($rows['Type'],0,strpos($rows['Type'],'('));
		if($type == '') $type = $rows['Type'];
		echo "<td>";
		Switch($type){
			case 'enum':
				foreach($val as $RadioVal)
				{
					?><input type="radio" name="<? echo $rows['Field'];?>" value="<? echo
$RadioVal;?>"<? if($GLOBALS[$rows['Field']] == $RadioVal) echo
"checked";?>><? echo $RadioVal;
				}
				break;
			case ETC.....


			}

rest of code


> -----Original Message-----
> From: Nikolai Devereaux [mailto:yomama@u...]
> Sent: 20 May 2002 20:23
> To: beginning php
> Subject: [beginning_php] Re: radio buttons + mysql
>
>
>
> > I explicitly need solution based on radio buttons.
>
> So what?  Maybe it's because I haven't had my morning coffee yet,
> but would
> it really be too hard to take the checkbox code and change it to generate
> radio buttons instead??
>
> I try to offer as much help as I can to anyone who asks, but
> you've already
> been handed a link which gives you almost all the code you need!
>
>
> Anyway, since I might be overreacting, I'll give you some help.
>
> write two functions.
>
> get_types() // returns an array of the different user types.
> create_radio()  // generates and a series of radio buttons
>
> get_types will probably get the set of user types from the
> database or maybe
> it's hand coded, who knows.  Doesn't matter, really, as long as the only
> access to the list of types is through this function, you can change it
> however you want whenever you want (as long as the format of the return
> array stays the same) and the rest of your site will be none the wiser.
>
>
> create_radio accepts a name (to name the inputs), an array of options for
> the different values, and (optionally) a default value to select.
>  Note that
> the default value is only selected if there's not already a variable with
> the same name as the one you're passing in set.
>
>
> This is pulled directly from the archive link:
>
> // create a dropdown combo box and preselect a default option
>   function create_select($name, $options, $default = "")
>   {
>     $tags = "<SELECT name=\"$name\">\n";
>
>     // http://www.php.net/foreach
>     foreach($options as $value => $text)
>     {
>       $tags .= "  <OPTION value=\"$value\"";
>
>       if($value == $default)
>       {
>         $tags .= ' SELECTED';
>       }
>
>       $tags .= ">$text</OPTION>\n";
>     }
>
>     $tags .= "</SELECT>\n";
>
>     return $tags;
>   }
>
>
> Let's rename "select" to "radio", change SELECT/OPTION tags to INPUT
> type="radio", and move the name from the SELECT tag to each of the INPUT
> tags.  Oh yeah, we need to change "SELECTED" to "CHECKED"
>
>   function create_radio($name, $options, $default = "")
>   {
>     // http://www.php.net/foreach
>     foreach($options as $value => $text)
>     {
>       $tags .= "  <INPUT type=\"radio\" name=\"$name\" value=\"$value\"";
>
>       if($value == $default)
>       {
>         $tags .= ' CHECKED';
>       }
>
>       $tags .= ">$text</INPUT>\n";
>     }
>
>     return $tags;
>   }
>
>
> At this point, you have all the code you need.  Just to be extra nice,
> though, I'll add this:
>
>   function create_radio($name, $options, $default = "")
>   {
>     global $$name;
>     if(isset($$name) && ($$name != ''))
>     {
>       $default = $$name;
>     }
>
>     // http://www.php.net/foreach
>     foreach($options as $value => $text)
>     {
>       $tags .= "  <INPUT type=\"radio\" name=\"$name\" value=\"$value\"";
>
>       if($value == $default)
>       {
>         $tags .= ' CHECKED';
>       }
>
>       $tags .= ">$text</INPUT>\n";
>     }
>
>     return $tags;
>   }
>
>
> That minor change will allow your radio button to be preselected with the
> existing value of $name.
>
>
> Just because I'm super super nice, I'll put it all together for you.
>
> Copy this into a PHP file and run it.  twice.
>
> <?php
>
> // This should really be defined in some form utilities inc file
>   function create_radio($name, $options, $default = "")
>   {
>     global $$name;
>     if(isset($$name) && ($$name != ''))
>     {
>       $default = $$name;
>     }
>
>     // http://www.php.net/foreach
>     foreach($options as $value => $text)
>     {
>       $tags .= "  <INPUT type=\"radio\" name=\"$name\" value=\"$value\"";
>
>       if($value == $default)
>       {
>         $tags .= ' CHECKED';
>       }
>
>       $tags .= ">$text</INPUT>\n";
>     }
>
>     return $tags;
>   }
>
> // this should be defined in some db interface include file
> function get_types()
> {
>   return array('Beer', 'Gin', 'Rum', 'Scotch', 'Vodka', 'Whiskey');
> }
>
>
> // this should be the actual start of the script:
> $types = get_types();
>
>
> echo "<FORM method=\"GET\" action=\"$PHP_SELF\">\n";
>
> echo create_radio('drink', $types);
>
> echo "  <INPUT type=\"submit\" value=\"Pick yer poison!\">\n";
> echo "</FORM>\n"
>
> ?>
>
>
> I think you should be able to handle inserting the value of
> $drink into the
> database, right?
>
> take care,
>
> nik
>
>
>

Message #2 by "Dan Ostrowski" <dan@t...> on Mon, 20 May 2002 22:07:13
Nick you are too kind.

heh.
Message #3 by "Nikolai Devereaux" <yomama@u...> on Mon, 20 May 2002 14:35:12 -0700

Okay -- you're mixing oil and water here.

The database schema (tables, columns, col data types) are all completely
separate from the create_radio() functionality.  What's nice about
create_xxxx() for generating form inputs is that you don't care where your
data comes from.

For historical reference, from my previous post:
> get_types will probably get the set of user types from the
> database or maybe it's hand coded, who knows.  Doesn't
> matter, really, as long as the only access to the list
> of types is through this function, you can change it however
> you want whenever you want (as long as the format of the
> return array stays the same) and the rest of your site will
> be none the wiser.


get_types() holds the interface to the db which queries the database and
creates/returns an array of values.

In a normalized database schema, you'd have something like this:

USER_TYPES
id
name

USERS
id
username
password
user_type  // type is an FK that links with USER_TYPES


That way, get_types could've been this:

function get_types()
{
    $query = "SELECT id, name FROM USER_TYPES";
    $res   = db_query($query);

    $ret = array();
    while($row = db_fetch_array($res))
    {
       $ret[$row['id']] = $row['name'];
    }

    return $ret;
}

That sets up an appropriate types array where the keys of the array are the
id's that both index the USER_TYPES table and are the valid values for the
user_type column in the USERS table.

What's also nice about using the get_types() approach is that it completely
separates your db interface from your main script.  It also separates your
form HTML code from the script.  The end result is a couple utility
functions that you can include from any script in your site, and your main
script isn't so littered with HTML that it's hard to read.


A more complete example would've filled in the get_types() code for Anonymous's
application, but since I don't know his database schema or his list o' data
types, I left it to him to finish things up.



Your example could be reorganized to something like this:

db_connect();
$fields = get_fields();
echo create_radio($formname, $fields);


Since you're outputting table formatting between your inputs, your versions
of the create_xxx() form utility functions can be easily reworked to allow
this functionality.


Take care,

Nik


  Return to Index