PHP Date dropdown list - php

Below is an old PHP function I have for a dropdown list for users to select there birthdate, this is just the day date portion of it, you can see that it uses str_pad to add on a 0 to the numbers 1-9, is there a better way of doing this?
<?PHP
$date_combo .= '<select name="' . $pre . 'day" class="' .$style. '">';
$date_combo .= "<option value=''>Day</option>";
for ($i = 1; $i <= 31; $i++) {
$date_combo .= " <option ";
if ($i == $selected_date_day) {
$date_combo .= " selected ";
}
$date_combo .= " value='" . str_pad($i, 2, "0", STR_PAD_LEFT) . "'>" . str_pad($i, 2, "0", STR_PAD_LEFT) . "</option>";
}
$date_combo .= "</select> ";
echo $date_combo;
?>

An alternative to str_pad is to use sprintf.
The code:
str_pad($i, 2, "0", STR_PAD_LEFT)
becomes:
sprintf("%02d", $i)
It will print $i as an integer that is 2 characters wide and padded with zeros.
See the sprintf documentation.

You could make a generic function that accepts an array in order to build a select.
function formSelect($name, array $options, $selected)
{
$output = '<select name="' . $name . '">';
foreach($options as $key => $value)
{
$output .= '<option value="' . $key . '"';
if($selected == $key) {
$output .= ' selected="selected"';
}
$output .= '>' . $value . '</option>';
}
$output .= '</select>';
return $output;
}
You should probably escape your output and a few other things, sorry threw that together.
Then you can build your array of options and pass that in. Looks much nicer to build your options list and then just call:
echo formSelect('birth[day]', $days, 1);

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>";
}
?>

PHP Bootstrap multi select options

In my code I am using PHP which populates the bootstrap multi selectpicker from MySQL database but the problem is it only selects the last option instead of multiple options, I don't know what I am missing in it? Here is my my code
function MultiBindCombo($tablenames, $columnnames1, $columnnames2, $comboname, $selectedopt) {
global $conn;
$sql="SELECT ". $columnnames1. ", " . $columnnames2 . " FROM ". $tablenames;
$result = mysqli_query($conn, $sql);
if( ! $result ) {
echo mysql_error();
exit;
}
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '" multiple="multiple">';
$array = explode(',', $selectedopt);
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
echo '</select>';
}
To get all selected values in a multiselect you need to use name attribute with []:
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '[]" multiple="multiple">';
After that you can iterate over $_POST[$comboname] with a foreach.
Update:
Let's look closer to your code here:
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
// You iterate over every value of array, so in the end
// `$print_selected` is defined depending on value of the
// last `$select_option`
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
// remove this. Why you echo `$select_option`?
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
Rewrite it as:
while ($row=mysqli_fetch_array($result)) {
$print_selected = '';
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
// break `foreach` as you found the right item
break;
}
}
// if right item is not found - `$print_selected` is empty
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}

print selectbox with multidimensional array in php

i am trying to generate a selectbox:
$turn= array(
'attr' => array('nameid' => 'turn',),
'0 - 499',
'500 - 1499',
'1500 - 3499',
'3500 - 12999',
'13000 - 17999',
'18000 - 23999',
'24000 - 40000',
);
function createSelectBox($array) {
$out = "<select id=" . $array['attr']['nameid'] . " name=" .$array['attr']['nameid']">";
$out .= "<option class='choose' >Choose...</option>";
for ($idx = 0; $idx < sizeof($array) - 1; $idx++) {
$out .= "<option value=" . $array[$idx] . ">" . $array[$idx] . "</option>";
}
$out .= '</select>';
return $out;
}
The Problem is, that it will generate the 'value'-attribute in my option-tag like this:
<option value="0" 499>0 - 499</option>
the function cant handle the whitescpace in my array.
Use this
function createSelectBox($array) {
$out = '<select id='.$array['attr']['nameid'].' name='.$array['attr']['nameid'].'>';
$out .= '<option class="choose" >Choose...</option>';
for ($idx = 0; $idx < sizeof($array) - 1; $idx++) {
$out .= '<option value="'.$array[$idx].'">' . $array[$idx] . '</option>';
}
$out .= '</select>';
return $out;
}
Your value are strings you are treating them as integers. try it.
<?php
$turn= array(
'attr' => array('nameid' => 'turn',),
'0 - 499',
'500 - 1499',
'1500 - 3499',
'3500 - 12999',
'13000 - 17999',
'18000 - 23999',
'24000 - 40000',
);
function createSelectBox($array) {
$out = "<select id=" . $array['attr']['nameid'] . " name=" .$array['attr']['nameid'] . ">";
$out .= "<option class='choose' >Choose...</option>";
for ($idx = 0; $idx < sizeof($array) - 1; $idx++) {
$out .= "<option value='" . $array[$idx] . "'>" . $array[$idx] . "</option>";
}
$out .= '</select>';
return $out;
}
echo createSelectBox( $turn );
?>

a simple modification of a for loop

I have a simple php script that counts the number of pages in a manga script :
$omv_pager = "";
$omv_pager .= "<div class=\"well\">\n";
$omv_pager .= "<span>Manga <select class=\"form-control\" style='margin-bottom:10px;' name=\"manga\" onchange=\"change_manga(this.value)\">";
$omv_pager .= "<option class=\"form-control\" value=\"0\">Selecione Título do Manga...</option>";
for ($i = 0; $i < count($mangas); $i++) {
$m = $mangas[$i];
$omv_pager .= "<option value=\"" . omv_encode($m) . "\"" . (($m == $manga) ? " selected=\"selected\"" : "") . ">" . $m . "</option>";
}
$omv_pager .= "</select></span>\n";
if ($manga) {
if ($chapter) {
$omv_pager .= "<span>Chapter <select name=\"chapter\" onchange=\"change_chapter('$manga_escaped', this.value)\">";
for ($i = 0; $i < count($chapters); $i++) {
$cnumber = $chapters[$i]["number"];
$omv_pager .= "<option value=\"" . omv_encode($cnumber) . "\"" . (($cnumber == $chapter_number) ? " selected=\"selected\"" : "") . ">" . $cnumber . (isset($chapters[$i]["title"]) ? (" - " . $chapters[$i]["title"]) : "") . "</option>";
}
$omv_pager .= "</select></span>\n";
if ($page) {
$prevhtml = "";
if ($page <= 1) {
$prevhtml = "<img src=\"http://www.leitor.tk/themes/default/no-previous.png\" alt=\"\" />";
} else {
$prevhtml = "<img src=\"http://www.leitor.tk/themes/default/previous.png\" alt=\"Previous Page\" title=\"Previous Page\" />";
}
$nexthtml = "";
if ($page >= count($pages)) {
$nexthtml = "<img src=\"http://www.leitor.tk/themes/default/no-next.png\" alt=\"\" />";
} else {
$nexthtml = "<img src=\"http://www.leitor.tk/themes/default/next.png\" alt=\"Next Page\" title=\"Next Page\" />";
}
$omv_pager .= "<span>$prevhtml Page <select name=\"page\" onchange=\"change_page('$manga_escaped', '$chapter_number_escaped', this.value)\">";
for ($p = 1; $p <= count($pages); $p++) {
$omv_pager .= "<option value=\"" . $p . "\"" . (($p == $page) ? " selected=\"selected\"" : "") . ">" . $p . "</option>";
}
$omv_pager .= "</select> of " . count($pages) . " $nexthtml</span>\n";
}
}
}
$omv_pager .= "</div>\n";
echo $omv_pager;
What I want to do is, in the last page change the name of the to "end"
e.g : 1-2-3-4-5-6-7-8-9-10-11-12-end
And thanks to all of you guys.
Try with:
">" . ($p == count($pages) ? "end" : $p) . "</option>"
instead of
">" . $p . "</option>"
For optimization reasons you might want to buffer count($pages) into a variable before the for.

Creating dynamic dropdown lists

I want to create dynamic select lists. For example: I have 5 students in my db. My goal is to create 5 selects ,and in every select all students which are in database. So if user inserts a 6th student in the database, the page should display 6 selects, and in every select names of 6 students.
I've tried with this code, but it only creates 1 select, containing 4 students(the first one from the db is missing).
The Code:
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
while($result=mysqli_fetch_array($execute))
{
echo '<select name=student'.$i.'>';
echo '<option value="-1" >Choose student</option> <br/>';
while($res=mysqli_fetch_array($execute))
{
echo '<option value='.$res["id_student"].'>'.$res["name"].'</option> <br/>';
}
echo '</select>';
$i++;
}
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++) {
$select .= '<select name=student' . $j . '>';
$select .= '<option value="-1" >Choose student</option> <br/>';
while($result=mysqli_fetch_array($execute)) {
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] . '</option>';
$i++;
}
$select .= '</select>';
}
echo $select;
UPDATE
inside the while
$select = '<select name=student' . $j . '>';
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] .
change this lines by this other
$select = '<select name="student' . $j . '">';
$select .= '<option value="' . $res["id_student"]."'>' . $res["name"] .
we missed the double quotes for value and in select name
Problem solved, I just needed to insert vars $exe and $execute inside for loop, so after every iteration $result is refreshed,otherwise it just prints options in first select...
CODE:
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++)
{
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$execute=mysqli_query($con,$exe);
$select .= '<select name=student' . $j . '>';
$select .= '<option value="-1" >Choose student</option> <br/>';
while($result=mysqli_fetch_array($execute))
{
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] . '</option>';
}
$select .= '</select>';
}
echo $select;

Categories