Using PHP if condition inside HTML code - php

I am using HTML inside PHP like this.
for($i=0;$i<count($arrSql);$i++)
$opt.="<option". if($_GET['pId'] == $arrSql[$i][0]){ echo "Selected";} ."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";
I have tested it for a long time and it looks correct, but it is showing an error and I don't know where the bug is.

You can't use concatenation and if together. Change it to:
for ($i=0;$i<count($arrSql);$i++) {
$opt .= "<option"
. ($_GET['pId'] == $arrSql[$i][0] ? " selected" : '')
."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";

You forgot the spaces.
Try following:
for($i=0;$i<count($arrSql);$i++)
$opt.="<option". ($_GET['pId'] == $arrSql[$i][0] ? ' selected="selected" ' : ' ') ."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";

Your echo call is not needed in this place. Your statement only concatenates strings and does not print them.
Additionaly it's not possible to use an if statement inside a string concatenation. However the if shortcut, the so called ternary operator is applicable in this situation.
And as pointed out in an other answer there is also a space missing before the selected part.
for($i=0;$i<count($arrSql);$i++) {
$opt .= "<option "
.($_GET['pId'] == $arrSql[$i][0]) ? "Selected" : ""
."value=" .$arrSql[$i][0]
. ">" .$arrSql[$i][1]. "</option>";
}
An alternative using if that might be more clear is:
for($i=0;$i<count($arrSql);$i++){
$opt .="<option ";
if ($_GET['pId'] == $arrSql[$i][0]){
$opt .= "Selected";
}
$opt .= "value=" .$arrSql[$i][0]. ">" .$arrSql[$i][1]. "</option>";
}
If you want to, you can even inline the array accesses into the string by using curly braces leading to this last line: (more here)
$opt .= "value=${$arrSql[$i][0]}>${$arrSql[$i][1]}</option>";
For the future you might want to enable error output in your scripts. This would have indicated the main error.

Related

Echo option value with selected

Im tryin to fix when i press my search button. That the selected search from my option field remains selected. But at the moment it automaticly picks the first field of the options in my form.
First one is hardcoded and it works.
<option value="HS" <?= ($nickval == 'HS' ? 'selected="selected' : '')?>>Homer Simpsons</option>
But then i wanted to echo out option value from database so its not hardcoded.
<?php
while(db2_fetch_row($queryexe)) {
echo "<option value='$pin'>$fullname</option>";
}
?>
And now when i want to add if its selected i tried to solve it like this.
echo "<option value='$pin'($nickval == '$pin' ? 'selected='selected'' : '')>$fullname </option>";
This is how i get my pin
$pin = db2_result($queryexe, 'P510PIN');
This is how i get my $nickval
$nickval = $_GET["int"];
Any suggestions what im doin wrong? Sorry if im unclear but i've tried my best
Aside from quoting errors indicated in the syntax highlighting...
You're trying to execute PHP code inside of a string:
echo "<option value='$pin'($nickval == '$pin' ? 'selected='selected'' : '')>$fullname </option>";
Variable interpolation is one thing, but code inside of a string isn't going to automatically execute. It's just a string being echoed to the page. (Check the page source and see what's actually being emitted to the browser.)
Separate the strings from the code which builds the strings:
echo "<option value='$pin' " . ($nickval == $pin ? "selected='selected'" : "") . ">$fullname </option>";

jquery adding attributes to multiple select drop-downs

I have code (edited, after Brad Christie suggestions):
drupal_add_js('
jQuery(document).ready(function(){
jQuery("#selFinishes option").each(function(index) {
if (jQuery(this).val() == ' . $filter_color . ') {
jQuery(this).attr("selected","selected")
}
})
});
', "inline");
And it sucessfully adds "selected" attribute ($filter_color is added via PHP) to the selected value. But when i target multiple select fields like this:
drupal_add_js('
jQuery(document).ready(function(){
jQuery("#selFinishes option").each(function(index) {
if (jQuery(this).val() == ' . $filter_color . ') {
jQuery(this).attr("selected","selected")
}
})
jQuery("#selThemes option").each(function(index) {
if (jQuery(this).val() == ' . $filter_theme . ') {
jQuery(this).attr("selected","selected")
}
})
});
', "inline");
Both of loops fail to work!
Thanks for tips!
The code above is apparently mixed javascript and php, but it not possible to tell what might be wrong with it. You should check (by viewing source in the browser) whether the resulting javascript code is what you intended. If possible post the resulting javascript here.
My educated guess is that the resulting JavaScript is invalid when it's output. Guessing by the variable names ($filter_color & $filter_theme) one (or both) of them is/are most likely a string making the test if (...val() == string) fail which in terns make the entire block of JavaScript result in a syntax error and fail entirely.
Try changing your output to encase the value in a string (maybe something like the following):
[snip].val() == "' . $filter_theme . '") {[/snip]
Notice I added double quotes on either side of the variable before and after the PHP concatenation. This should fix the syntax would should intern make it work again.
Again, too little information in your question but this would be my guess at the solution

How to select a <select> statement from database?

I wasnt quite sure how to word the question correctly - but this is merely just out of interest really. Constantly I am having to load information from a database and pre-populate a form with the values. So in the case of the textbox, its easy, i simply set the value:
<input type="text" value="<?=$foo;?>" name="foobar">
However when I come to select boxes I find my code gets quite sloppy, as I need to place a selected value in the line somewhere. So really I have two options, both of which I dislike:
$one = $two = "";
switch ($myval) {
case "1": $one = " selected";
case "2": $two = " selected";
}
and then in the HTML:
<select name="myval">
<option value="1"<?=$one;?>>One</option>
<option value="1"<?=$two;?>>Two</option>
</select>
Or the other option is to place a shorthand if statement in the middle of the select:
<select name="myval">
<option value="1"<?=($myval=="1") ? " selected" : "";?>>One</option>
<option value="1"<?=($myval=="2") ? " selected" : "";?>>Two</option>
</select>
Which looks slightly cleaner, however it still bugs me.
Anyone got any much more efficent ways of doing this? its even more annyoing when It is just a Yes/No drop downbox and I have to write stupid if statements for each value.
The same question applies to checkboxes as well.
Create an array with the data you want in the output. Loop over it. Generate an option element for each item in it.
As an addition to Quentin (just some code to help you out), I tend to use arrays as well, like this:
<select name="myval">
<?php
$options = array(
"1" => "One",
"2" => "Two"
);
foreach ($options as $value => $text) {
echo '<option value="' . $value . '"' . ($myval == $value ? ' selected' : '') . '>' . $text . '</option>';
}
?>
</select>
Well the easiest way for such repetitive outputs is to write yourself a function, for example:
function selectbox(array $options, $name, $value = null) {
$out = '<select name="' . $name . '">';
foreach($options as $key => $text) {
$out .= '<option value="' . $key. '"' . ($key == $value ? ' selected="selected"' : null) . '>' . $text . '</option>';
}
return $out . '</select>';
}
There are really many ways for a cleaner code. Find one or invent your own :)
For select statements, I like to use utility methods. E.g.:
<?= HTML::createSelect($name, $actualvalue, $optionslist, $passthrough) ?>
Something on that line. Read the optionslist and the actualvalue from the DB. Passthrough is for adding HTML decorators, e.g. id, class, etc.

Using PHP function to create a dynamic dropdown menu using arrays: dropdown doesn't populate

I am trying to dynamically build a drop down menu using PHP. The idea is: the elements are formed from a loop which calls and array. If the array element matches the data held in session then it adds the "selected" attribute to the tag, meaning that the page displays the previously selected option.
I have tried to include one complete set of code here, all the way from defining the variables from session data to echoing the HTML for the form element.
It doesn't currently work - the drop down menu appears, but is blank, and has no options. I've debugged it with ideone and it seemed to run successfully, and I can't see where I am going wrong, however this is my first PHP function! So I'm sure I've screwed it up somehow :)
Any help much appreciated.
<?php
session_start();
//if the session data has been set, then the variable $sv_02 is defined
//as the data held in the session under that name, otherwise it is blank
if (isset($_SESSION['sv_02'])) {$sv_02=$_SESSION['sv_02'];} else {$sv_02="";}
//define the array
$dm_sv_02 = array('-Year','-2012','-2011','-2010','-2009');
//create the function
function dropdown($dropdownoptions, $session_data)
{
foreach($dropdownoptions as $dropdownoption){
if($session_data == $dropdownoption){
echo '<option value="' . $dropdownoption . '" selected>' . $dropdownoption . '</option>';
} else {
echo '<option value="' . $dropdownoption . '">' . $dropdownoption . '</option>';
}
}
}
//echo the HTML needed to create a drop down, and populate it with
//the function which should create the <option> elements
echo '<select name="sv_02">';
dropdown($dm_sv_02, $sv_02);
echo '</select>';
?>
Try this:
foreach ($dropdownoptions as $dropdownoption) {
echo ($dropdownoption == $sv_02) ? "<option selected=\"selected\" value=\"$dropdownoption\">$dropdownoption</option>" : "<option value=\"$dropdownoption\">$dropdownoption</option>";}
This turned out to be a result of the fact I was using {smarty} tags to build my php, the code was as written but only worked when it was all included in one smarty tag, I'm not sure I understand why that should be the case but in any regard it was fixed by including it all in one tag.

Beginner if statement help

if ($row['active'] == 1) echo ''.htmlspecialchars($row['username']).''; else echo htmlspecialchars($row['username']);
Could I write this shorter and cleaner somehow?
echo $row['active'] == 1 ? ''.htmlspecialchars($row['username']).'' : htmlspecialchars($row['username']);
explained a little here http://www.addedbytes.com/php/ternary-conditionals/
I'm assuming you made a mistake putting the $id in a single quoted string, and meant for php to put the value of $id in its place in there.
$name=htmlspecialchars($row['username']);
if($row['active'] == 1) {
echo "<a href='prof?id=$id'>$name</a>";
} else {
echo $name;
}
You could take advantage of the ternary operator:
echo ($row['active'] == 1)
? ''.htmlspecialchars($row['username']).''
: htmlspecialchars($row['username'])
;
(I split the code onto separate lines for the sake of formatting.

Categories