Add "selected" in a <select> based on value from database - php

how do I select the correct value in a when I get the value from a database on page load?
I have this code now, but when it runs it gives the attribute "selected" to every number after the given number from the database.
<?php
$i = 8;
while ( $i <=24 ) {
if ($i == $store_info['weekdays_open_time']) {
$selected = " selected";
}
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
}
?>

Change you code to:
<?php $i = 8; while ( $i <=24 ) {
$selected = ($i == $store_info['weekdays_open_time'])?" selected" : "";
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
} ?>

You need to reset the $selected variable inside the while loop:
<?php
$i = 8;
while ($i <= 24) {
$selected = '';
if ($i == $store_info['weekdays_open_time]) $selected = ' selected="selected"';
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
}
?>
Edit: Make sure you always set a value for each variable you use; it's a good habit. In your code you used the variable selected inside the print function, without always having a variable value assignment first.

you never clear your $selected variable, basically once it finds a correct answer, $selected is set to " selected" and is no longer an empty variable, so each iteration when you call for it, it prints " selected" not "";
<?php
$i = 8;
while ( $i <=24 ) {
$selected = ( $i == $store_info['weekdays_open_time']) ? " selected='selected'" : "";
print ("<option value='" . $i ."'" . ( () ? )$selected . ">" . $i . "</option>");
$i++;
} ?>

You could just replace the whole if statement :
<?php
$i = 8;
while ( $i <= 24 ) {
echo "<option value='" . $i ."'" ;
echo ($i == $store_info['weekdays_open_time'] ? ' selected' : '');
echo ">" . $i . "</option>";
++$i;
}

Check it :
<?php
$i = 8;
while ($i <= 24) {
?>
<option value="<?PHP echo $i; ?>" <?PHP if ($i == $store_info['weekdays_open_time']) { echo "selected='selected'";} ?> > <?PHP echo $i; ?></option>
<?
$i++;
}
?>
Hope it will definitely work :)

You may simply use
$i = 8;
while ( $i <=24 ) {
$selected = $i == $store_info['weekdays_open_time'] ? 'selected' : '';
echo "<option value='$i' $selected>$i</option>";
$i++;
}
Also, it's not necessary to use . when you have variables inside "double quotes" and it's better to use echo instead of print because echo is a language construct and it's faster than print function.
An Example.

Related

Create months as options for select tag using php

I need to create a select tag with months as options using php
like this:
<option value='01'>JAN</option>
<option value='02'>FEB</option>
... and so on
here is my try - without success
<select>
<?php
$str = '{"01":"JAN","02":"FEB","03":"MAR","04":"APR","05":"MAY","06":"JUN","07":"JUL","08":"AUG","09":"SEP","10":"OCT","11":"NOV","12":"DEC"}';
$obj = new stdClass(json_decode($str));
foreach($obj->$key as $key=>$val){
echo "<option value = '" . $key . "'>" . $val . "</option>";}
?>
</select>
<?php
for($month = 1; $month <= 12; $month++) {
echo '<option value="' . $month . '">' . strtoupper(DateTime::createFromFormat('!m', $month)->format('M')) . '</option>';
}
Dont make life so complicated
<?php
$arr= ['01'=>'JAN', '02'=>'FEB', '03'=>'MAR', '04'=>'APR',
'05'=>'MAY', '06'=>'JUN', '07'=>'JUL', '08'=>'AUG',
'09'=>'SEP', '10'=>'OCT', '11'=>'NOV', '12'=>'DEC'
];
foreach($arr as $key=>$val){
echo "<option value = '" . $key . "'>" . $val . "</option>";
}
?>

If statement not working in my conditional ternary operator

I have the following if statement in PHP:
<?php
for ($i = 1; $i <= 10; $i++) {
echo "<option " . $carDoors == $i ? "selected = 'selected'" : "" . " >" . $i ."</option>";
}
?>
I need the selectlist to be based on the value of $carDoors and if that's the case, I want to echo selected = 'selected'. At the moment I keep getting a fully empty selectbox. What am I doing wrong?
The problem of your code is, that the ternary operator ?: has a higher precedence than the concatenation operator .. Your code is therefore evaluated as:
if ($carDoors == $i) {
echo "<option selected = 'selected'";
} else {
echo "<option >" . $i ."</option>";
}
To get your desired output you should use brackets arround your short if:
echo "<option " . ($carDoors == $i ? "selected = 'selected'" : "") . " >" . $i ."</option>";
A list of operator precedence can be found in the official PHP documentation.
You can use ? by this way:
<?php
for ($i = 1; $i <= 10; $i++) {
$selected = $carDoors == $i ? "selected = 'selected'" : "";
echo "<option " . $selected . " >" . $i ."</option>";
}
?>
or simple insert it into ():
for ($i = 1; $i <= 10; $i++) {
echo "<option " . ($carDoors == $i ? "selected = 'selected'" : "") . " >" . $i ."</option>";
}

How to retain the value of Select Option inside a For Loop using PHP

I have a working code below. Basically, the code prints the options 50 times and 4 is the default selected option.
for ($i = 1; $i <= 50; $i++) {
if($i == 4){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
but every time i click the submit button, the option field resets back to the selected option even though the variables was captured properly.
It would be good if the option selected by the user is preserved after the button was clicked and the only time it reset back to the selected defaults is if the page was refreshed.
check if the value is sent by post if not assign 4 to the variable option
<form action="#" method="post" accept-charset="utf-8">
<select name="select">
<?php
if(isset($_POST['select']))
{
$option= $_POST['select'];
}
else
$option=4;
for ($i = 1; $i <= 50; $i++) {
if($i == $option){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
?>
</select>
<input type="submit" name="" value="Sumbit">
</form>
This should do it - it uses the value sent from the client if it exists, or 4 if not.
if (isset($_POST['selected_value'])) {
$selected = $_POST['selected_value'];
} else {
$selected = 4;
}
for ($i = 1; $i <= 50; $i++) {
if($i == $selected){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
Take value from posted field, say "select", if exist then take it as selected otherwise your default value.
Using below code:
$selected = (isset($_POST['select']) ? $_POST['select'] : 4);
for ($i = 1; $i <= 50; $i++) {
if($i == $selected){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}

PHP Comparing 0 does not work

I'm trying to set a checkbox as checked in php based on an hour fields from a comma separated value string. It works well for 1-23 but for some reason hour 0 always displays as checked:
<?php
myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>
The problem is straightforward; look at the outer loop:
for ($hour = 0; $hour <= 23; $hour++) {
Consider only the first iteration, so $hour is int(0). Further in the code:
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
Pay close attention to the loop condition:
$h <= count($myhours)
Consider the last iteration of that loop, so $h equals the size of your array.
if ((int)$hour == (int)$myhours[$h]) {
At this point $myhours[$h] is undefined because the array index is out of bounds (and a notice would have been emitted) and so (int)$myhours[$h] becomes (int)null which is int(0). The comparison is therefore always true when $hour has the value of int(0).
The solution is to change the loop condition to:
$h < count($myhours)
Not exactly and answer, but your code could be reduced to this:
$myhours = array(0, 10, 13, 20);
for($hour = 0; $hour <= 23; $hour++) {
echo '<td><input type="checkbox"' . ( in_array($hour, $myhours) ? ' checked' : '' ) . ' value="' . $hour . '" onchange="updatehour(' . $_REQUEST['user'] . ', this.checked, ' . $hour . ')">' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00</td>';
}
No need for a second loop and more variables here. Also be aware to not output values from $_REQUEST directly without any check.
Demo
Try before buy
Problem solved. It was actually the count($myhours) that was causing the problem. Basically even with an empty string it still returns an array with 1 element. Changed to check if count($myhours) > 1 and everything is working as expected:
<?php
$myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 1) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>

How can I limit the total number of SimpleXML results?

I'm looking to limit to the first 5 results returned here.
This works, but it does not limit the data set:
<?php
foreach($sxml->status as $status){
$name = $status->user->name;
$image =$status->user->profile_image_url;
$update =$status->text;
$url = "http://twitter.com/" .$status->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
?>
I've tried this:
<?php
for($n = 0; $n <= 5; $n++){
$name = $sxml->$status[$n]->user->name;
$image = $sxml->$status[$n]->user->profile_image_url;
$update = $sxml->$status[$n]->text;
$url = "http://twitter.com/" . $sxml->$status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
?>
and am really kind of unsure why it doesn't work. If I simply do:
<?php echo $sxml->status[0]->user->name ?>
then I get the proper result. But when attempting it within the for loop, I get NULL.
Perhaps some kind of while? A different setup altogether? Thanks so much for any help you can give on this.
Change this:
for($n = 0; $n <= 5; $n++){
$name = $sxml->$status[$n]->user->name;
$image = $sxml->$status[$n]->user->profile_image_url;
$update = $sxml->$status[$n]->text;
$url = "http://twitter.com/" . $sxml->$status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
To this:
for($n = 0; $n <= 5; $n++){
$name = $sxml->status[$n]->user->name;
$image = $sxml->status[$n]->user->profile_image_url;
$update = $sxml->status[$n]->text;
$url = "http://twitter.com/" . $sxml->status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
You accidentally were writing this:
<?php echo $sxml->$status[0]->user->name ?>
Where it was trying to us $status[0] as a variable variable and of course, that doesn't exist and is thus undefined/null.
If you had something that works, why overcomplicate things by changing everything? Just limit the processing to the first N entries.
$i = 0;
foreach ($sxml->status as $status) {
if (++$i > 5) {
// stop after 5 loops
break;
}
// the rest is identical
}
Btw, $n = 0; $n <= 5; $n++ will limit to the first 6 entries, not 5.
$n = 0; $n < 5; $n++ will do what you asked for.
Don't you mean
$n = 0; $n < 4; $n++
I've also tried this, and it works great :-)
foreach ($xml->item as $item) {
if (++$i > 5) { break; }
$item->title . '';
} //foreach()
Note I'm not using $i = 0; it seems to know that by default ;-)
I hope this helps some one.

Categories