Validating html with php - php

Something is wrong with my print "<option value...";
line of php code.
It keeps generating error messages:
an attribute value specification must be an attribute value literal unless SHORTTAG YES is specified
<option value = Addition>Addition</option>
<and so on...>
Okay, so how do i fix this line of code:
//foreach loop to cycle through the array
foreach ($testFiles as $myFile)
{
$fileBase = substr($myFile, 0, strlen($myFile) - 5);
**//Problem here:**
print "<option value = $fileBase>$fileBase</option>\n";
} // end foreach
such that's it's html compliant, the php code works fine, I just need validation on the html, cause you can't validate php, and the variable $fileBase references an html file, in this case Addition would be one of the files allotted to $fileBase.

print "<option value = \"$fileBase\">$fileBase</option>\n";
Should do it

print "<option value='$fileBase'>$fileBase</option>\n";

There are a few other options:
You could use printf:
printf('<option value="%s">%s</option>', $fileBase, $fileBase);
A here-doc:
echo <<<HTML
<option value="$fileBase">$fileBase</option>
HTML;
You could drop out of PHP temporarily (generally a good technique, but not very pretty here):
<?
foreach ($testFiles as $myFile) {
$fileBase = substr($myFile, 0, strlen($myFile) - 5);
?>
<option value="<?= htmlentities($fileBase) ?>"><?= htmlentities($fileBase) ?></option>
<?
}
?>
But really, what you should be doing is using one of the many templating systems out there, and not mixing HTML in with your code.

Related

php echo fails if I echo "<"

I have a strange problem which I presume is to do with my setup (WAMP on Windows 10). I am a beginner and working on my first project (rewriting an old Access/VBA solution).
I want to create an HTML drop down list on the fly - mysqli_query works fine and I can echo the list I need and get an accurate row count. But when I try any echo statement which starts with a '<' the rest of the page doesn't run.
The < is fine anywhere else but at the beginning. What I need is to be able to put
while($row = mysqli_fetch_assoc($result)) {
echo "<option value ='".$row['schoolName']."'>".$row["schoolName"]."</option>";
}
This just displays a list of $row["schoolName"] biut no other text.
There may be some mistakes in that code but I have tested this with much shorter echo strings and they always fail if '<' is the first thing after echo. I don't get an error message - the code above just gives a correct list of $row['schoolName].
Any ideas?
Try this
<select name="" id="input" class="form-control">
<?php
while($row = mysqli_fetch_assoc($result)) {
echo "<option value ='".$row['schoolName']."'>".$row["schoolName"]." </option>";
}
?>
</select>
You must add the <select> tag before using an <option> tag.
<select name="" class="">
<?php
while($row = mysqli_fetch_assoc($result)) {
echo "<option value ='".$row['schoolName']."'>".$row["schoolName"]."</option>";
}
?>
</select>

How to set an option from multiple options or array with different values to views as selected in select box using PHP

An option value is taken from the database and included in a select box along with other options. How can I set the value taken from the database as selected?
The value from the database is set as $row['value'] and equals s. In HTML the options look like so...
<select name="select">
<option value='xxs'>Extra, Extra small</option>
<option value='xs'>Extra small</option>
<option value='s'>Small</option>
<option value='m'>Medium</option>
<option value='l'>Large</option>
<option value='xl'>Extra Large</option>
<option value='xxl'>Extra, Extra small</option>
</select>
What I want is the $row['value'] (Small) option to be displayed on page load... Is this possible?
The good news is, this is possible and in PHP is quite simple really. First we put all of our options and their respective values in an array like so:
<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');
Follow this by opening the select box and calling upon the options array in a foreach loop...
echo '<select>';
foreach($options as $view=>$value){
As you may have noticed the array contains fields that look like 'Large'=>'l' and the for each loop is calling upon the options as $view=>$value. $view represents the name field, in this case 'Large' and $value represents the value field 'l'. This is important if you expect the user to see different options in the select box than what the values are set at.
Next we create the variable $selected which is going to be used to determine if there is a match between $row['value'] and $value...
$selected=($row['value'] == $value)? "selected" : "";
This is the same as using an if and else statement to set the variable, but shorter. The first section after the variable is asking if $row['value'] is equal to $value, if it does then $selected="selected" else (:) $selected is set to blank.
Next we include the options. Because it is in the foreach loop, we only need one line to insert all of the options...
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
Remember the $selected variable in the last step? Each time the foreach loop goes through a section of the options array set at the beginning, it checks to see if $row['value'] equals $value. If it does then $selected will be set as selected and that particular option will be the one that is shown on page load. It continues through the rest of the array until all views and values have been scanned and returns their respective options.
Finally we close the foreach loop and the select box...
}
echo '</select>';
And there you have it, an automatic way to make a select box option set as selected. A similar pattern can be used for check-boxes, radio selectors, tabs and more.
The full code...
<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');
echo '<select>';
foreach($options as $view=>$value){
$selected=($row['value'] == $value)? "selected" : "";
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
}
echo '</select>';
Given this array, and this value to be the selected value...
$options = array(
'Extra, Extra small' => 'xxs',
'Extra small' => 'xs',
'Small' => 's',
'Medium' => 'm',
'Large' => 'l',
'Extra Large' => 'xl',
'Extra, Extra Large' => 'xxl'
);
$selected = 'm'; // $selected can be swapped for $row['value'] as in the OP
There are several ways to dynamically construct the option tags inside of a <select> and set the selected attribute on one of them.
First the one-liner inside a foreach loop:
echo "<select name=\"select\">";
foreach($options as $text=>$value){
echo "<option value=\"$value\"" , ($selected == $value ? " selected" : "") , ">$text</option>";
}
echo "</select>";
This code block uses a ternary conditional operator aka conditional operator aka shorthand if/else aka inline conditon. Go here for further reading and examples.
By using double quotes " you avoid having to toggle back and forth between literal strings and variables. *You will have to escape double quotes that are nested inside of the string by prepending \. *Variables can be wrapped in curly brackets to isolate their variable name from the surround text. *Single quotes will not echo the value of the variable.) For continued read about quoting: reference
By using , (commas) instead of . (dots) to concatenate the string, performance is increased. one benchmark
By only adding a space before the selected attribute in the true condition (versus adding the space outside the condition on every iteration), you avoid creating unnecessary spaces inside your tag.
By using an inline condition statement, you avoid unnecessarily declaring a variable into the global scope. If you declare the selected string as a variable, as #independent.guru does, it will be declared/overwritten and used only once on every iteration; this can only decrease performance.
Each programmer will have their own preferences about "readability", "brevity", "consistency", and "performance" and may elect to construct their html using any mixture of the above techniques.
As a general rule, I don't bother to declare a variable that I will only use once. In my personal preference hierarchy, brevity, consistency, and performance always come before readability.
Some of the above points may seem like micro-optimizations, but for a canonical question, it is reasonable to include discussion on performance as any of the listed methods may be copy-pasted directly into projects.
If the first code block was too compact, here are two other versions that spread out the method over multiple lines without generating any extra variables:
Separated shorthand if/else syntax:
echo "<select name=\"select\">";
foreach($options as $text => $value){
echo "<option value=\"$value\"";
echo $selected == $value ? " selected" : "";
echo ">$text</option>";
}
echo "</select>";
Standard if conditional:
echo "<select name=\"select\">";
foreach($options as $text => $value){
echo "<option value=\"$value\"";
if($selected == $value){
echo " selected";
}
echo ">$text</option>";
}
echo "</select>";
All of the above versions of the same method will create this rendered html:
When the page is loaded:
When the select element is opened:
The source code will look like this:
<select name="select"><option value="xxs">Extra, Extra small</option><option value="xs">Extra small</option><option value="s">Small</option><option value="m" selected>Medium</option><option value="l">Large</option><option value="xl">Extra Large</option><option value="xxl">Extra, Extra Large</option></select>
This is the source code tabbed out for easier reading:
<select name="select">
<option value="xxs">Extra, Extra small</option>
<option value="xs">Extra small</option>
<option value="s">Small</option>
<option value="m" selected>Medium</option>
<option value="l">Large</option>
<option value="xl">Extra Large</option>
<option value="xxl">Extra, Extra Large</option>
</select>

How to get the complete value of an option tag?

I have this code using php
<select id="sem" name="y[]">
<option>Year</option>
<?php
$petsa = new DateTime();
$yr=$petsa->format('Y');
$a=$yr+1;//2015
$b=$yr-1;//2013
for($y=$b;$y<=$a;$y++)
{
$bb = $y+1;
echo '<option value="'.$y.'"'.'-'.$bb;
if(isset($_POST['y'])){
if (in_array($y."-".$bb,$_POST['y'])){
echo 'selected="selected"';
}
echo '/>'.$y."-".$bb;
}else
echo "<option value ='$y'"."-"."$bb".">".$y."-".$bb;
echo "</option>";
}
?>
</select>
if(isset($_POST['submit'])){
$sem= $_POST['sem'];//this is from other field
foreach ($_POST['y'] as $yer);
$osql2 = "INSERT INTO sy VALUES('$sem','$ss')";
if (mysql_query($osql2)){
echo "Successfully Added!";
}
This code work well almost but the problem is when i call the value of the option tag it just give me this value $ss=2014 and it should be like this $ss=2014-2015
what is wrong with my code? that code generate SY from 2013-2014 to 2015-2016
please help me.
Look at the generated HTML. Look at where the quotes around the attribute value are. They are currently very wrong.
Stop trying to generate HTML by mashing together lots of different strings. It becomes very hard to see what is going on.
$value = $y . "-" . $bb;
?>
<option value="<?php echo htmlspecialchars($value); ?>">
<?php echo htmlspecialchars($value); ?>
</option>
<?php
I suspect it's your use of quotes here:
echo "<option value ='$y'"."-"."$bb".">".$y."-".$bb;
I would change it to this:
echo "<option value ='$y"."-"."$bb"."'>".$y."-".$bb;
I have moved the second ' to just before the > of the opening option tag.
The single quote ' was for the option tag, and the double quote " was for the PHP string, you were simply cutting the value for option short

how to keep the choosed data in the <select> element? HTML

here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));

How can I add text into a certain area?

If I have a line like this,
<option value="someval">somval</option>
how can I position the cursor after the last quotation of value and put something like abcdef?
So the output would be
<option value="somval" abcdef>somval</option>
with PHP?
I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.
#martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:
$query = $db->query("my query....");
while($row = $db->fetch($query)) {
<select name="thename">
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
... Followed by 100 more, because there are a lot of locations to list.
</select>
How can I post all the options I have into a textbox and have the above code automatically generated to save a lot of time?
Using your example you would do:
while($row = $db->fetch($query)) {
printf('<option value="someval"%s>someval</option>',
($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}
This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try
while($row = $db->fetch($query)) {
printf('<option value="%s"%s>%s</option>',
$row['country-code'],
($row['country-code'] === $selection) ? ' selected="selected" ' : '',
row['country-name']);
}
With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.
Note: The usual disclaimers about securing your output apply
You could capture (value=".+?") and replace it with $0 abcdef.
<?php
$string = '<option value="someval">someval</option>';
print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);
?>
Which outputs the following:
<option value="someval" abcdef>someval</option>
With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?

Categories