Hello; I am trying to get an html dropdown box to work and it kind of does. The box works okay, but the information does not retain itself. Basically I have some code that checks some basic criteria for fields. The form calls itself so that the column next to the field displays an error message if something is wrong. If something is wrong on say the first name, the state jumps back to "None" instead of displaying the actual value ( although it retains the value ). I could send entire code, but I think this gives the idea. // State must be 2 characters if(preg_match("/^[A-Z_]{2,}$/", $_POST["state"]) === 0) $errState = '<class="errText">State can not be None'; ************************************************** <tr> <td width="124" bgcolor="#FFFFFF"> <b><font size="2" face="Arial" color="#3366FF"> State:</font></b></td> <td width="278"> <select size="1" name="state"> <option selected>None</option> <option value="WA">Washington</option> <option value="CA">California</option> <option value="BC">British Columbia</option> <option value="AB">Alberta</option> </select></td> <td> <?php if(isset($errState)) echo $errState; ?></td> </tr> ************************************************** //This will check if data is retained for state. Last Name has to have information for this to display !!! // Last Name must be letters, dash and spaces only if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["lname"]) === 0) $errLName = '<class="errText">Last name must be from letters, dashes, spaces and must not start with dash'; else $errStatus = $_POST["state"];
You'd need to put a PHP snippet in all your <option> tags to test if that value is already set and if so, set it as selected. <option<?=(empty($_POST['state'])?" selected":"")?>None</option> <option value="WA"<?=($_POST['state']=="WA"?" selected":"")?>>Washington</option> <option value="CA"<?=($_POST['state']=="CA"?" selected":"")?>>California</option> <option value="BC"<?=($_POST['state']=="BC"?" selected":"")?>>British Columbia</option> <option value="AB"<?=($_POST['state']=="AB"?" selected":"")?>>Alberta</option> Code (markup):
This is quite a simple task requiring a small amount of code. Let's say you want to build a selection (drop-down) box containing a list of all the states. We'd have them stored in a MySQL database with the structure like this: id: tinyint unsigned, primary key, auto_increment state: varchar(2) Our PHP code to read the id number from the HTML form using $_POST and build ALL the HTML for the drop-down box would look something like this: <?php $stateID=intval($_POST['states']); $query=mysql_query("SELECT `id`,`name` FROM `states` ORDER BY `state` ASC"); $htmStates=''; while ($row=mysql_fetch_assoc($query)) { $htmStates.='<option value="'.$row['id'].'"'.($stateID==$row['id'] ? ' selected="selected"' : '').'>'.$row['state'].'</option>'; } ?> PHP: If the value read isn't valid it'll just show the first option in the list. Now the HTML to display it would be this: Select state: <select name="states"><?=$htmStates?></select> Code (markup):
Eh, if you want to do a simple loop like Yesideez just showed, there's a much better way to do it. Why bother with DB connections just to get a couple (or all, even) states? <select name="state"> <option>None</option> <? $states = array("WA"=>"Washington","CA"=>"California","BC"=>"British Columbia","AB"=>"Alberta"); foreach($states as $acronym => $name) { ?><option value="<?=$acronym?>"<?=($_POST['state']==$acronym?" selected":"")?>><?=$name?></option><? } ?> </select> PHP: Yeah, I really don't like building HTML up inside of PHP strings. Doing it that way is a big pet peeve of mine.. it looks very unclean with having it all shoved in quotes. :/ If you absolutely must have your HTML in a string, output buffers are your best friend! <? $states = array("WA"=>"Washington","CA"=>"California","BC"=>"British Columbia","AB"=>"Alberta"); ob_start(); foreach($states as $acronym => $name) { ?><option value="<?=$acronym?>"<?=($_POST['state']==$acronym?" selected":"")?>><?=$name?></option><? } $state_options = ob_get_clean(); ?> <select name="state"> <option>None</option> <?=$state_options?> </select> PHP:
zerxer - using shorthand <? is very bad practice you should always use <?php instead! Just imagine taking your site to a server that doesn't have it enabled having to go through every script changing them. That's a matter of preference completely - your method is a lot longer and takes longer to execute not that we're needing minimum execution time here but on a very large and active site every little optimisation helps. Even without building a string and echo'ing straight out with an array containing the states... foreach ($arrStates as $state) { echo '<option value="'.$state.'"'.($_POST['state']==$state ? ' selected="selected"' : '').'>'.$state.'</option>'; } PHP: At least pepe's got both database and array method now
I haven't run into a server yet, through all my clients, that didn't have support for <?. I'd say the company running the server would have to be awfully far behind in website programming time to not have support for it. Doing something like <? ?>output here<? ?> takes longer to execute than <? $string = "output here"; echo $string; ?> ??
Ask anyone who codes PHP properly they'll always say always use long tags - it's a really bad habit to get into using them. Hence my last piece of code I posted...
Eh, the execution time difference can't be that much between directly outputting and building it in a string.. Besides, if we really must talk optimization, why would you recommend querying an SQL database just for a list of the states? DB interfacing would add time to the execution and use more CPU power increasing the server load (if it were on a large high traffic site).