Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


php in select>options

Posted on 2011-09-20
Medium Priority
Last Modified: 2013-12-13

I'm just learning php (by force), but am pretty well versed in html and css. I did not rite the following code and I'm not sure how to pull out the php in the following in order to make the page validate.

         <td width="15%"><b><b>Priority</b></td>
         <select name="priority" size="1" value="priority">
            <option value=""
<?php if ($row['priority'] == "") echo " selected";?>
            <option value="Normal"
<?php if ($row['priority'] == "Normal") echo " selected";?>
            <option value="Elevated"
<?php if ($row['priority'] == "Elevated") echo " selected";?>
            <option value="STAT"
<?php if ($row['priority'] == "STAT") echo " selected";?>

The idea is to prefetch the "priority" info and populate the drop down with that. Afterwards, the user can change the value and once submitted, the value will change in the database. Any pointers would be appreciated - and thanks in advance.

Question by:hypervisor
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 22

Expert Comment

by:Kim Walker
ID: 36567501
The php code should be ignored for HTML validation, but it is the un-indented lines that begin with "<?php" and end with "?>".
LVL 24

Expert Comment

ID: 36567699
i think that if you will be working with php, you need to change to a different validator. taking out php and then putting it back in is a pain.

Accepted Solution

dkellner earned 500 total points
ID: 36571306
There are several answers for the core of the problem :)

1. You DON'T need a validator. (Many ppl will disagree here but believe me: if you know the standards, you don't have to follow them(

2. This code is not very nice and the reason is NOT what the validator says.  Your future eyes are the real validator - this code will look like a mess when you look at it a few months later.

3. If you're determined to force your code thru Tidy (or whatever you validate with), consider using a javascript solution to make the default item "selected".  jQuery is a good friend when you need such things.  You'll still need a <?php .......?> tag but as xmediaman said, a well behaving validator SHOULD skip php codes.

4. If it doesn't, try validating the RESULT that the browser gets - use "view source", copy it to a textfile, and validate that.  After all, THAT is what should be valid, not your PHP source.

Now here's a function that I'm using (for years) to create dropdowns.

function optionlist($t,$default="",$lf="") {
	foreach ($t as $n=>$x) {
		$sel=($n==$default?" selected":"");
		$out.="<option value=\"$n\"$sel>$x$lf";
	return $out;

Open in new window

Use it like this:

<select .............>
<?php optionlist($myArray,$defaultItem); ?>

Open in new window

...where $myArray is an array with key=>value pairs of the list contents and $defaultItem is the key of the element that should be selected initially.

Just an example, really.  You'll find yourself writing such helpers for yourself and use them instead of HTMLing repetitive things directly.  That's the way of the samurai.
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.


Expert Comment

ID: 36571320

<select .............>
<?php print optionlist($myArray,$defaultItem); ?>

is the proper way to use it.  optionlist only returns the HTML string.

Expert Comment

ID: 36595624
rather than simply echoing 'selected' to ensure the code validates should you not use


Open in new window

For example:

<option value="STAT" 
<?php if ($row['priority'] == "STAT") echo ' selected="selected"';?>

Open in new window

From testing if you simply echo 'selected' you receive the following validation error:

"SELECTED" is not a member of a group specified for any attribute

Open in new window

However using selected="selected" solves the error.

Hope that helps.


LVL 111

Expert Comment

by:Ray Paseur
ID: 36899270
You might want to get this book and give yourself a month or so to work through the problems and examples so you can learn the basics of PHP.  It's very readable with excellent examples and a code library you can download for your own use.  Now in its fourth printing, it has been a permanent part of my professional library since Edition One.

The PHP site has the online introductory tutorial -- that will be helpful, too.

What the code posted with this question appears to be doing goes something like this...

We have already made a query and retrieved a row from the data base.  That row is an associative array named $row.  While there may be other things in $row, we assume that there is a value in $row["priority"] which may be NULL (empty string) or one of Normal, Elevated or STAT.  The combination of the HTML and PHP would work together through the PHP parser.  The PHP if() statements would be used to determine what HTML should be generated.  The pre-selected option in the HTML form select control would be determined by the contents of $row["priority"].

If the code you posted is in a file named like thing.html you might want to try running it in a file named like thing.php

Best of luck with your studies, ~Ray
LVL 30

Expert Comment

by:Olaf Doschke
ID: 36902492
Like dkellner already said a good validator should skip PHP code in it's validation. The other very obvious way of getting rid of the php code is executeing it. If you eg feed an online HTML validator with the url of the php skript the php executes and the resulting html is validated.

The problem is, you can't really predict the html in general, or create it by just skipping the php. A more complex php will have loops and if statements and other program flow mechanism, that by condition create some html by other conditions other xml. In your case either one priority option will be marked selected. To validate html output in this case would need running the php with all possible $row['priority'] values to get all the different outputs. This would be called code coverage tests, to see if the code runs in each of the different branches that can run.

PHP in this way is not the preferenced way, as it mixes HTML with code. That was the original intent of the php inventor, but it turns out, not just in HTML/CSS seperation of concerns is better. Ray already pointed you to general material about php, dkellner already gave you the good advice to seperate the functionality into functions you call. This makes the php less convoluted, on the other side in his case wht remains is just the <select...>php</select>, which by itself also doesn't validate, if you just remove the php code.

It's really a situation where you can't have the pie and also eat it. If you want dynamic creation of html you don't have static hml you can validate, your html variants multiply by the number of different ways the php execution can go, but you can take one case as a test sample, once you also verify, that the php skript behaves in the similar way always. In your pecial case always one of the selection options is selected, or none, but never two.

Take a look here:
They describe the hard problem in detail and offer an on-the-fly validation here:

You'd put that into a debug version of your php site and every php script outputting html will also output a temp file .validate.html which then is validated. During a tet phase you can check if your php misbehaves in some situations.

In very short summarized:
1. You need to extend your toolbelt, if you extend your static HTML to be dynamic, be it by php or AJAX/javascript or anything else.

2. The seperation approach you could go instead or on top of this, is in parallel to the separation of html and css you already should be familar with, you'd seperate the php logic from the html by defineing templates. The php will not put together html piece by piece or embed itself into the html, the html templates would have placeholders the php script will then replace, this makes the templates easier to validate.

finally, you're not alone: See this discussion:

Users are going both the hard route trying to finetune what validator should validate or the simple route and turning it off. If you'd ask my personal oppinion, the html validation is not the main concern, even not for static html. Even if html validates to the rules, the browsers don't necessarily display the html the same way. And that also goes for dynamically created html.

Bye, Olaf.

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question