Main Content

PHP - good coding practise and sticky radio buttons

Archive - Originally posted on "The Horse's Mouth" - 2006-10-17 03:41:53 - Graham Ellis

With PHP, it's very easy to knock together a page with a couple of radio buttons and a small application just be taking the "bull at a gate" approach - but if you develop code like this, and without planning, you end up with a very long application that's hard to follow and maintain and - unless you've very good at repeatedly debugging the same code - it's going to be unreliable too.

Much better to move all the standard stuff into functions and just keep the data in the main program or even in data files.

To give you an idea, here's a sample I've just written with sticky radio buttons - as a demonstration - showing you how I've separated the mechanism from the actual data:

<?php

function mystickyradio($spec) {
$html = "<tr><td>".htmlspecialchars($spec[0])."</td><td>";
$bname = htmlspecialchars($spec[1]);
for ($k=2; $k<count($spec); $k+=2) {
$chkd = ($_REQUEST[$spec[1]] == $spec[$k+1]) ? " checked" : "";
$html .= "<input type=\"radio\" name=\"$bname\"";
$html .= " value=\"".htmlspecialchars($spec[$k+1])."\"$chkd>";
$html .= htmlspecialchars($spec[$k])."<br>";
}
$html .= "</td></tr>";
return $html;
}

$rb1 = array("Do you do regular weight training?","muscle",
"Occasionally or never","1",
"Yes, as part of my exercise routine","1.2",
"Yes, and I'm a bulky lad","1.5");

$rb2 = array("Select your age range","old",
"Under 21","0-20",
"21 to 65","midlife",
"over 65","old");

$form = "<form method=\"POST\"><table border=1>";
$form .= mystickyradio($rb1);
$form .= mystickyradio($rb2);
$form .= "<tr><td>&nbsp;</td><td><input type=\"submit\"></td></tr>";
$form .= "</table></form>";

?>
<html>
<head>
<title>Data driven sticky radio boxes</title>
</head>
<body>
<h1>Demo Sticky form from parameters</h1>
Please fill in this form<br>
<?= $form ?>
<hr>
Instructions, copyright, etc
</body>
</html>


A real life application would have some "business logic" to actually handle the data entered, of course, and I would move the functions out into a separate include file so that they could be used across all my work. Similarly, the HTML template would be separated out for easier maintainance by an HTML expert. Ah - we're headed for the "4 layer model" again ...

Run the code here