Solved

php in select>options

Posted on 2011-09-20
7
349 Views
Last Modified: 2013-12-13
Hello,

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.

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

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.

Rich
0
Comment
Question by:hypervisor
7 Comments
 
LVL 21

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 "?>".
0
 
LVL 24

Expert Comment

by:mankowitz
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.
0
 
LVL 3

Accepted Solution

by:
dkellner earned 125 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="") {
	$out="";
	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); ?>
</select>

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.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 3

Expert Comment

by:dkellner
ID: 36571320
Sorry,

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

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

Expert Comment

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

selected="selected"

Open in new window


For example:

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

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.

Cheers

Matt
0
 
LVL 108

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.
http://www.sitepoint.com/books/phpmysql4/

The PHP site has the online introductory tutorial -- that will be helpful, too.
http://php.net/tut.php

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
0
 
LVL 29

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: http://twineproject.sourceforge.net/
They describe the hard problem in detail and offer an on-the-fly validation here: http://twineproject.sourceforge.net/doc/phphtml.html

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: http://stackoverflow.com/questions/783902/excluding-disabling-validation-in-eclipse

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.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
.htaccess file settings 4 36
How can I expand text with explaination 5 22
PHP loop not working 4 33
update field on focusout 15 24
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

759 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now