I am working on submission system. I have a drop down list when user want to edit the section drop-down need to be matched select option to visible in drop down list based on before saved in database value. I write some code for this option but it's not working properly. This same code I have used for the antoher project it's working well. An error also not coming I have checked syntax no problem.
<?php
$journalid = $_GET['jiid'];
$sqlold = "SELECT `jtype`, `jtitle` FROM `journal` WHERE jid=? LIMIT 1";
$db->query($sqlold);
$db->bind(1, $journalid);
$db->execute();
$resjid = $db->resultset();
foreach($resjid as $resjtype){
$resjournaltype = $resjtype['jtype'];
}
echo 'Res Ournal Type: '.$resjournaltype;
$db->query("SELECT article_name, article_value FROM article_type");
$db->execute();
$resultrow = $db->resultset();
foreach($resultrow as $vals){
if($resjournaltype == $vals['article_value'] ){
echo "yes";
}
?>
<option <?php //if ( $jtype == $res['article_value'] ) echo 'selected = "selected"'; ?> value="<?php echo $res["article_value"];?>"><?php echo $res['article_name']; ?> </option>
<?php
else {?>
<option <?php //if ( $jtype == $res['article_value'] ) echo 'selected = "selected"'; ?> value="<?php echo $res["article_value"];?>"><?php echo $res['article_name']; ?> </option>
<?php
}
}*/
else{
?>
<option <?php //if ( $resjid[0]['jtype'] == $vals['article_value'] ) echo 'selected = "selected"'; ?> value="<?php echo $vals["article_value"];?>"><?php echo $vals['article_name']; ?> </option>
<?php
}
}
?>
I am searching for a solution every where on the Internet but I forgot some syntax problems. These problems not giving an error. If here I am checking if condition inside for-each loop here is I made a mistake. My actual code is this. The problem was I am checking two string, not numbers. In PHP string values compare with strcmp() function.
if($resjournaltype == $vals['article_value'] )
{ echo "yes"; }
I changed condition like this finally my problem has been solved.
if(strcmp($resjournaltype, $vals['article_value']) == true){
echo $resjournaltype .'-'. $vals['article_value'] ; }
Related
I have a little problem here. I have a list, which is:
<form action="display.php" method="post">
<select name="holiday">
<option value="month">Kiekvieno mėnesio skaičiavimas</option>
<option value="day">Kiekvienos dienos skaičiavimas</option>
</select>
<br> <br>
<input type="submit" name="select" value="Pasirinkti" />
</form>
What I need to do is that when the user selects value ="month", php code would do one action, and when the user selects value ="day", php code would do another action?
My php code looks like this:
<?php
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
}
else if ($selectedValue == $_POST['month']) {
$todaysDate = new DateTime();
while ($employee = $select->fetch()){
$employmentDateValue = new DateTime($employee['employment_date']);
// Comparing employment date with today's date
$differenceBetweenDates = date_diff($employmentDateValue, $todaysDate);
$workMonths = $differenceBetweenDates->y * 12 + $differenceBetweenDates->m;
$holidayDays = $workMonths *4;
echo "<tr>";
echo "<td>".$employee['name']."</td>";
echo "<td>".$employee['surname']."</td>";
echo "<td>".$employee['employment_date']."</td>";
echo "<td>".$workMonths."</td>";
echo "<td>".$holidayDays."</td>";
echo "</tr>";
}
}
else {
echo "Lalalala";
}
?>
I've tried to do so with $_POST['select'], but it doesn't work. Thanks for any help guys
<?php
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
if ($selectedValue == 'month') {
}
else if ($selectedValue == 'day') {
}
else{
echo "Lalalala";
}
}
?>
You need to do $_POST['holiday'], so change:
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
}
to
if($_POST['holiday']){
// Storing selected value in a variable
$selectedValue = $_POST['holiday'];
}
You also need to change the line:
else if ($selectedValue == $_POST['month']) {
So it's not part of the original if statement:
if ($selectedValue == 'month') {
// your code
}
else {
echo "Lalalala";
}
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>
I have an option menu as follows:
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php
do {
?>
<option value="<?php echo $row_Recordset2['Cycle'] ?>"
<?php
if ($varCycle_DetailRS4 == $row_Recordset2['Cycle']) {
echo 'selected';
} elseif ($varCycle2_DetailRS4 == $row_Recordset2['Cycle']) {
echo 'selected';
} else {
echo '';
}
?>
>
<?php echo $row_Recordset2['Cycle'] ?>
</option>
<?php
} while ($row_Recordset2 = mysql_fetch_assoc($Recordset2));
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
?>
</select>
Currently, the default selection is showing all records. I would like for the default to be the latest set of data equal to:
<?php echo $row_RecordsetCycle['Cycle']; ?>
So option menu would list 1,2,3,4,5 with 5 being the default when the page loads. User can then pick any option available. is set to last record in table with a limit of 1 so it will always echo the last record, which composes the option menu.
Help please. What should I edit so that the one record in
<?php echo $row_RecordsetCycle['Cycle']; ?>
is the default or selected option menu when the page loads? Currently, the default just shows all records and is extremely slow to load, hence why I want the latest record to be the default.
I took a stab at rewriting this. (code at the end)
the first thing I did was turn your do_while loop into a while loop as I think it was adding unnecessary confusion to the code
after doing that I moved some code
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
above the while loop as I thought it was needed to "prime the pump" of the while loop
I also pulled the
if ($varCycle_DetailRS4 == $row_Recordset2['Cycle']) {
return ' selected';
} elseif ($varCycle2_DetailRS4 == $row_Recordset2['Cycle']) {
return ' selected';
} else {
return '';
}
out into a function so as to simplify the code further
now here come my assumptions I assumed that $varCycle_DetailRS4 was the last value and that $varCycle2_DetailRS4 was the currentlySelected that was set befor the code provided;
if that is the case and that $varCycle2_DetailRS4 would be unset if it was the first then all that would need to be done is to slightly modify the isSelected to only set one option as selected.
<?php
function isSelect($value)
{
$lastValue = $varCycle_DetailRS4;
$currentlySelected = $varCycle2_DetailRS4;
if(isset($currentlySelected))
{
$selectValue = $currentlySelected;
}
else
{
$selectValue = $lastValue;
}
if ($selectValue == $value) {
return ' selected';
} else {
return '';
}
}
?>
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
while ($row_Recordset2 = mysql_fetch_assoc($Recordset2))
{
$value = $row_Recordset2['Cycle']
echo " <option value=\"".$value."\"".isSelect($value).">".$value."</option>/n";
} ;
?>
</select>
Try using end() to get the last array:
<?php
$arr =array(1,2,3,4,5);
$last = end($arr);
?>
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php foreach($arr as $key=>$val):
if(in_array("$last", array($val))==true){
echo '<option value="" selected="selected">'.$val.'</option>';
continue;
}
echo '<option>'.$val.'</option>';
endforeach; ?>
</select>
Stop using mysql extension, use pdo or mysqli. Using your question code, it should be:
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
$last = end($row_Recordset2);
foreach($row_Recordset2 as $key=>$val){
//other code
if(in_array("$last", array($val))==true){
echo '<option value="" selected="selected">'.$val.'</option>';
continue;
}
echo '<option>'.$val.'</option>'
}
Working Demo
I am looking for some method to select a php combobox "<select>" based on results from mysql.
Actually I am working on a php form that will be used to edit existing values in mysql table. My first form will simply pass the id of the record to be edited, and this goes something like this Click to edit
Code on editCalendar.php is as follows:
<?php
include("dbpath.php");
$id = htmlspecialchars($_GET["id"]);
$sql="Select * from event_Date where eventid=" . $id;
$result=mysql_query($sql);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result)
{
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_assoc($result))
{
$name=$row["EventTitle"];
$close=$row["OpenOrClose"];
$remarks=$row["Remarks"];
$date=$row["EventDate"];
$type=$row["Type"];
}
?>
The value obtained in $close will be used to select "SelectClosedOrOpen" on the same form, i.e. the user will get pre selected option from the populated list.
<select id="SelectClosedOrOpen">
<option value="3">Select</option>
<option value="0">Open</option>
<option value="1">Closed</option>
</select>
Means, if $close has 0, then <option value="0">Open</option> must be selected else if $close has 1 then <option value="1">Closed</option> should be automatically selected on formload.
You'll just need to write the selected attribute in there. Try this
<select id="SelectClosedOrOpen">
<option value="3" <?php echo ($close == 3) ? 'selected="selected"': ''; ?>>Select</option>
<option value="0" <?php echo ($close == 0) ? 'selected="selected"': ''; ?>>Open</option>
<option value="1" <?php echo ($close == 1) ? 'selected="selected"': ''; ?>>Closed</option>
</select>
I created this function some years back. I hope it helps you.
It basically requires an array of your options and the value of the option to be pre-selected. It returns the OPTIONS for your select, so you still have to create the SELECT tags, which allows you to customise the ID, JS etc..
function drop_down_box_options_from_array($choices,$default="")
{
$output= '';
// $choices is contructed using $choices[]=array("value","Displayed Choice");
while (list ($key, $val) = each ($choices))
{
$output.= '<option value="';
$output.= $choices[$key][0];
if ($default==$choices[$key][0])
{
$output.= '" selected="selected" >';
}
else
{
$output.= '">';
}
$output.= $choices[$key][1];
$output.= '</option>';
$output.= "\n";
}
return $output;
}
Using your scenario:
<select id="SelectClosedOrOpen" name="OpenOrClose">
<?php
// defined here for clarity, but can be defined earlier ie in a config file
$choices[]=array('3', 'Select');
$choices[]=array('0', 'Open');
$choices[]=array('1', 'Closed');
echo drop_down_box_options_from_array($choices, $row['OpenOrClose']);
?>
</select>
I have a system where I rearrange navigational items.
It stores the new order in an array and then I use a for loop to go through the array and update the database.
<?php
$apageid = array();
$apagename = array();
$apageorder = array();
$q = "SELECT g.id, g.title, n.order FROM tbl_general g INNER JOIN tbl_navigation n ON n.pageid = g.id WHERE n.type = '$_SESSION[parent]' ORDER BY n.order";
$return = $database->query($q);
while($row=mysql_fetch_assoc($return)){
$apageid[] = $row['id'];
$apagename[] = $row['title'];
$apageorder[] = $row['order'];
}
$count = count($apageid);
$bpageid = array();
$bpageorder = array();
?>
<div class="form-holder">
<?php
//run through each page one at a time and update the order of the menu
mysql_data_seek( $return, 0 ); //reset the pointer to do the same query
$i = 0; //the count for saving the new configuration
while($row=mysql_fetch_assoc($return)){
$id = $row['id'];
$title = $row['title'];
$order = $row['order'];
?>
<div class="form-row">
<div class="form-label">
Page Name
</div>
<div class="form-field">
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
<?php
for($j=0; $j<$count; $j++){
if($apageid[$j] == $id) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageid[$j]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apagename[$j]; ?></option>
<?php
}
?>
</select>
<select class="select-small" name="<?php echo $bpageorder[$i]; ?>">
<?php
for($k=0; $k<$count; $k++){
if($apageorder[$k] == $order) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageorder[$k]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apageorder[$k]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<?php
$i++;
}
?>
This first chunk of code is the menu where you can reorder items.
Initially it loads up the current select and allows you to change the ordering.
function reorderChildren($pageid, $pageorder){
global $database;
$count = count($pageid);
//run through each page one at a time and update the order of the menu
for($i=0; $i<$count; $i++){
//set a few variables
$pid = $pageid[$i];
$porder = $pageorder[$i];
echo "pid = $pid porder = $porder";
$q = "UPDATE tbl_navigation SET order = '$porder' WHERE pageid = '$pid' AND type = '$_SESSION[parent]'";
$database->query($q);
}
return 0;
}
The information then ends up being passed here and the problem appears to be the for loop is never executed.
Can anyone see why this would be?
It's not the naming used, I've checked them.
Am I storing information in the arrays correctly?
Can I make it clear that it's $bpageid and $bpageorder that are the arrays carrying the information forward.
Thanks!
Was a simple fix!
The problem was that the select name needed to be just name="bpageid[]" rather than what I listed above. Silly!
You have just initilized $bpageid = array(); at top after first while loop.No value is assigned
after that you using
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
but no value is in $bpageid[$i] so name of this select box is blank.
It might be problem. check this and do as required.
you could try to construct a json from the options of the select element store it to a hidden field or send ajax request to php script for processing , order could be made from a "weight" value 1,2,3 etc.... sort it with php and loop to display