AM / PM value not displaying correctly in Select attribute - php

I have a list of items, each with a date/time option. I need for each list item to have the correct time displayed for it.
But this doesn't seem to work. It will return the correct 'am' or 'pm' value for $duedateA, but when I try to set the selected attribute value is gets wonky and will either show the wrong am or pm, or both.
Am I doing something wrong?
if(!empty($resInvoice[0]["due_date"])){
$duedateA = date("a",strtotime($resInvoice[0]['due_date']));
}
if($duedateA == "am"){
$selected_am = 'selected="selected"';
}
if($duedateA == "pm"){
$selected_pm = 'selected="selected"';
}
<select name="due_time[a]">
<option value="am" '.$selected_am.'>am</option>
<option value="pm" '.$selected_pm.'>pm</option>
</select>

date_default_timezone_set('America/New_York');
$resInvoice[0]["due_date"] = '2012-10-26 03:21:44';
$selected_am = '';
$selected_pm = '';
$duedateA = '';
if(!empty($resInvoice[0]["due_date"])){
$duedateA = date("a",strtotime($resInvoice[0]["due_date"]));
}
if($duedateA == "am"){
$selected_am = ' selected="selected"';
}
if($duedateA == "pm"){
$selected_pm = ' selected="selected"';
}
echo '<select name="due_date[a]">
<option value="am"'.$selected_am.'>AM</option>
<option value="pm"'.$selected_pm.'>PM</option>
</select>';
sorry for all the variables, i have my errors set to strict.

Related

How can I simplify this PHP script?

I'd like to add "selected" attribute to a combo box. This is my PHP:
if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }
if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }
if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }
if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }
I may have over hundreds of IF's.
I've tried this one, but It seems not working:
for($a=1; $a<=4; $a++){
if($results['status'] == $a)
{ $ok = "selected"; }
else
{ $ok = ""; }
}
I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way
Edit (My combo box):
<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>
Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!
// initialize all 4 to blank
for($a=1; $a<=4; $a++){
${"ok" . $a} = "";
}
// set the one that is selected
${"ok" . $results['status']} = "selected";
This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.
You can do this way,
<?php
// status list array
$selectValues = array(1, 2, 3, 4);
echo '<select name="combo_name">';
foreach($selectValues as $value){
$selected = "";
if($results['status'] == $value){
$selected = ' selected="selected" ';
}
echo '<option '.$selected.' value="'.$value.'">'.$value.'</option>';
}
echo '</select>';
?>
All you have to do is make an array and loop through it-
<?php
$results_status = 3; // What ever your retrieve variable value is. In your case: `$results['status']`
$arr = array("1" => "A",
"2" => "B",
"3" => "C",
"4" => "D"
);
?>
<select>
<?php
foreach($arr as $key => $val){
$sel = ($results_status == $key) ? "selected='selected'" : "";
?>
<option value="<?php echo $key?>" <?php echo $sel; ?>><?php echo $val?></option>
<?php }?>
</select>
You need to check every time for the selected value in the combo box.
Hope this helps
$combolength - the number of options in combo
$ok = array_fill(0, $combolength - 1, '');
switch ($results['status']) {
case $results['status']:
$ok[$results['status']]= 'selected';
break;
}
I personally think "simplify" what you already have is not the way to go about this. If you are not using a framework, I think you should instead ask how to make your script reusable, especially since you say "I have many combo box(es) that should be treated this way." Not using a contained element like a function/method sounds like a lot of extra work from a hardcoding standpoint. I personally would create a class that you can make form fields standardized and that you can feed an array into with dynamic key/value arrays. Simple example:
/core/classes/Form.php
class Form
{
# The idea here is that you would have many methods to build form fields
# You can edit this as you please
public function select($settings)
{
$class = (!empty($settings['class']))? ' class="'.$settings['class'].'"':'';
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':'';
$selected = (!empty($settings['selected']))? $settings['selected']:false;
$other = (!empty($settings['other']))? ' '.implode(' ',$settings['other']):'';
ob_start();
?>
<select name="<?php echo $settings['name']; ?>"<?php echo $other.$id.$class; ?>>
<?php foreach($settings['options'] as $key => $value) { ?>
<option value="<?php echo $key; ?>"<?php if($selected == $key) echo ' selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
To use:
# Include the class
require_once(__DIR__.'/core/classes/Form.php');
# You can use $form = new Form(); echo $form->select(...etc.
# but I am just doing this way for demonstration
echo (new Form())->select(array(
'name'=>'status',
'class'=>'classes here',
'id'=>'select1',
'other'=>array(
'data-instructions=\'{"stuff":["things"]}\'',
'onchange="this.style.borderColor=\'red\';this.style.fontSize=\'30px\'"'
),
# Options can be assign database returned arrays
'options'=>array(
'_'=>'Select',
1=>'A',
2=>'B',
3=>'C',
4=>'D'
),
'selected'=>((!empty($results['status']))? $results['status'] : '_')
));
Gives you:
<select name="status" data-instructions='{"stuff":["things"]}' onchange="this.style.borderColor='red';this.style.fontSize='30px'" id="select1" class="classes here">
<option value="_">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>

PHP multiple select form how to use: if (taskOption[0] is selected)

HTML:
<select name="taskOption[]" multiple>
<option>first<br /></option>
<option>second<br /></option>
<option>third</ option>
</select>
PHP:
<?php
foreach ($_GET['taskOption'] as $selectedOption){
echo "lesson:".$selectedOption."<br>";}
?>
This php code simply prints the selected options.
How can i separately do something if an option is selected ? for example
if (taskOption[0] is selected){
$x="1";
if (taskOption[1] is selected){
$y="1";
What i have tried with partial success so far is this:
$options = array("", "", "");
foreach ($_GET['taskOption'] as $selectedOption)
echo "".$selectedOption."<br>";
if($selectedOption == 'first'){
$options[0] = "11";
echo $options[0];
}
elseif($selectedOption == 'second'){
$options[1] = "22";
echo $options[1];
}
elseif($selectedOption == 'third'){
$options[2] = "33";
echo $options[2];
}
but i still have problem when i choose 2+ option..
(it only echo the last option)
You should add values to the options in the select tag first, so you can easy identify each one.
<select name="taskOption[]" multiple>
<option value="one">first<br /></option>
<option value="two">second<br /></option>
<option value="three">third</ option>
</select>
After it, you should remove the "elseif" and simply do ifs for all
$options = array("", "", "");
foreach ($_GET['taskOption'] as $selectedOption)
echo "".$selectedOption."<br>";
if($selectedOption == 'one'){
$options[0] = "11";
echo $options[0];
}
if($selectedOption == 'two'){
$options[1] = "22";
echo $options[1];
}
if($selectedOption == 'three'){
$options[2] = "33";
echo $options[2];
}
Im mantaining your code but it can be improveed a lot. Im not sure why are you adding the values to an array ($options).
You should add the value attributes to your option elements
<option value="first">first<br /></option>
<option value="second">second<br /></option>
<option value="last">third</option>
You are not wrapping your logic inside of the foreach.
foreach ($_GET['taskOption'] as $selectedOption){
echo "selected: ".$selectedOption;
if($selectedOption === 'first'){
$options[0] = "11";
echo $options[0]."<br>";
}
elseif($selectedOption ==='second'){
$options[1] = "22";
echo $options[1]."<br>";
}
elseif($selectedOption ==='third'){
$options[2] = "33";
echo $options[2]."<br>";
}
echo"end";
}
You need to put the swirly brackets around your logic to make sure everything beneath runs.

How to get the selected value from dropdown on post edit

I have the database for categories where i have id and name rows
<select name="category_id">
<option value="<?php if($category_id === 1) { echo 'selected';} ?>">Electronics</option>
<option value="<?php if($category_id === 2) { echo 'selected';} ?>">Automotive</option>
</select>
for some reason this does not show which one was selected when trying to edit the submitted post
and i do retrieve the category_id like so:
$res6 = mysql_query("SELECT * FROM `posts` WHERE `id` = '" . $id . "' LIMIT 1");
if(mysql_num_rows($res6) > 0){
while($row6 = mysql_fetch_assoc($res6)){
$id = $row6['id'];
$category_id = $row6['category_id'];
$price = $row6['price'];
$cover = $row6['cover'];
$title = $row6['title'];
$description = $row6['description'];
}
}
I think the option argument for selected is
<option selected="selected"> </option>
I believe MySQL results are always returned as strings, so $category_id === 1 will be false.
Either try $category_id === "1" or $category_id == 1
Also, you need to echo the selected="selected outside the value attribute
You can also try like this as well.
<select name="category_id">
<?php
$cats = array("1"=>"Electronics", "2"=>"Automotive");
foreach($cats as $k=>$cat){
if( $k == $category_id )
echo "<option value='{$k}' selected='selected'>{$cat}</options>";
else
echo "<option value='{$k}' >{$cat}</options>";
}
?>
</select>

One select does not post the selected option

Example... this query is displayed even though the ">" Greater Than option was selected
SELECT *
FROM sr_rounds
WHERE cir1 LIKE '%2.4%'
ORDER BY sr_id asc
Any ideas?
<form action="search_new.php" method="post" name="exchanges" id="exchanges">
<select name="circuits" id="circuits" onclick="searchIt()" onblur="searchIt()">
<option value="select" selected="selected">Select Search Field</option>
<option value="cir1">Circuit 1</option>
<option value="cir2">Circuit 2</option>
<option value="cir3">Circuit 3</option>
<option value="cir4">Circuit 4</option>
<option value="vch">VCH-1-5</option>
</select>
<select name="sorting" id="sorting" onclick="searchIt()" onblur="searchIt()">
<option value="select1" selected="selected">Sort By</option>
<option value="sr_id">Sector</option>
<option value="date">Date</option>
//This select always returns a "like" clause regardless of which option you select
</select>
<select name="clauses" id="clauses" onclick="searchIt()" onblur="searchIt()">
<option value="select2" selected="selected">Clause</option>
<option value="=">Equals</option>
<option value="like">Like</option>
<option value=">">Greater Than</option>
<option value="<">Less Than</option>
<option value="date">Date</option>
</select>
<select name="sortorder" id="sortorder" onclick="searchIt()" onblur="searchIt()">
<option value="select3" selected="selected">Order</option>
<option value="asc" name="1">Asc</option>
<option value="desc" name="2">Desc</option>
</select>
<?php
$select = $_POST['circuits'];
$searchdb = $_POST['searchdb'];
$select1 = $_POST['sorting'];
$select2 = $_POST['clauses'];
$select3 = $_POST['sortorder'];
//To display friendly field name instead of actual field name
if ($select == 'cir1')
{
$boxresult = 'Circuit 1';
}
if ($select == 'cir2')
{
$boxresult = 'Circuit 2';
}
if ($select == 'cir3')
{
$boxresult = 'Circuit 3';
}
if ($select == 'cir4')
{
$boxresult = 'Circuit 4';
}
if ($select == 'vch')
{
$boxresult = 'VCH-1-5';
}
//To use different queries while searching
if ($select2 == '=')
{
$queres = "SELECT * FROM sr_rounds WHERE $select = '$searchdb' ORDER BY $select1 $select3";
}
else if ($select2 == 'like')
{
$queres = "SELECT * FROM sr_rounds WHERE $select LIKE '$searchdb' ORDER BY $select1 $select3";
}
else if ($select2 == '>')
{
$queres = "SELECT * FROM sr_rounds WHERE $select > '$searchdb' ORDER BY $select1 $select3";
}
else if ($select2 == '<')
{
$queres = "SELECT * FROM sr_rounds WHERE $select < '$searchdb' ORDER BY $select1 $select3";
}
else if ($select2 == 'contain');
{
$queres = "SELECT * FROM sr_rounds WHERE $select LIKE '%$searchdb%' ORDER BY $select1 $select3";
}
$query = $queres;
$result = #mysql_query($query);
$num = #mysql_num_rows($result);
It is because you have a semi-colon in the line:
else if ($select2 == 'contain');
Make it
else if ($select2 == 'contain')
You have a typo in your code:
else if ($select2 == 'contain');
// ----------------------------^
This ends the if block. The next {} block executes always.
write this in your search_new.php:
var_dump($_POST); exit();
Check what clauses value is. I'd also go for another representation of the values. I tend to use numbers and reduce the if/else structure to a switch block, but anyway you can stick to whatever. Just an advice. Instead of >, < and =, use "greater", "lower" and "equals", or another word, as < and > are part of the xml structure, and there may be a problem for your browser to understand that. If you check the codeblock you wrote, you will see that the > is actually not acting well. It's painted black, instead of brown/red.
To sum up:
Check the value of $_POST
Change the option values to numbers or words, not symbols.

Using select and option and remembering after POST

Using select and option HTML tags, I pass information through using $_POST.
When reloading the page however, the select resets back to the original values.
I am looking to get it to remember what has been passed through.
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo"<option value='$value-$first-$second'>$title - $first - $second</option>";
}
}
}
?>
As you can see, I use 3 foreach loops to populate whats in it.
How can I achieve my selection being remembered?
Thanks for reading.
You'll need to use the name of your select field in place of "your_select_field_name" in my change below:
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo "<option value='$value-$first-$second'";
if( $_POST['your_select_field_name'] == "$value-$first-$second" ) {
echo ' selected="selected"';
}
echo ">$title - $first - $second</option>";
}
}
}
?>
The output for the selected option on the new page needs to look like:
<option value='foo' selected>...<option>
HTML does not have memory. The item that's selected by default in a <select> form element is the one with the selected attribute (or the first one if none). Simply use the information contained in $_POST to generate the appropriate markup:
<select name="foo">
<option value="v1">Label 1</option>
<option value="v2">Label 2</option>
<option value="v2" selected="selected">Label 3</option>
<option value="v4">Label 4</option>
</select>
You need to set the selected tag on the correct option. Something like this:
<?php
$postedValue = $_POST['select_name'];
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
$computedValue = $value . '-' . $first . '-'. $second;
if ( $computedValue == $postedValue) {
$selected = "selected";
} else {
$selected = ''
}
echo "<option value='$computedValue' $selected>$title - $first - $second</option>";
}
}
}
?>
It could probably be written cleaner but this is the general idea.

Categories