I want to create a very simple <select> box containing just numbers, 1,2,3,etc.. So very simply I want
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
However, I would like to use PHP to generate the options instead of creating them all by hand.
How may I go about doing this?
You can use this:
<select>
<?php
define('MAX_OPTIONS', 6);
for($optionIndex=1; $optionIndex <= MAX_OPTIONS; $optionIndex++){
echo '<option>' . $optionIndex . '</option>';
}
?>
</select>
Please note that the open and close tag for <select> is direct output, its not PHP code, thus the PHP tags.
You could also just print it all through PHP:
<?php
define('MAX_OPTIONS', 6);
echo '<select>';
for($optionIndex=1; $optionIndex <= MAX_OPTIONS; $optionIndex++){
echo '<option>' . $optionIndex . '</option>';
}
echo '</select>';
?>
Hint
Finally, just to make a small step towards more structured programming, you could create a function:
<?php
function createSelectBox($optionCount){
$out = '<select>';
for($idx=1; $idx <= $optionCount; $idx++){
$out .= '<option>' . $idx . '</option>';
}
$out .= '</select>';
return $out;
}
?>
And then call it - from within PHP (!!) - like this:
<?php
echo createSelectBox(6);
?>
Since your generated HTML code will look nice and be functional, it won't serve any practical purpose because no select box can work without the <option> tags being served a value attribute (which should contain the value that represents the option).
If needed, read this to gain a better understanding of how select works
for ($i = 0; $i <= 10; $i++){
echo "<option>" . $i . "</option>";
}
<?php
function options($num) {
$options = '';
for ($i = 1; $i < $num + 1; $i++)
{
$options .= "\t<option>" . $i . "</option>\n";
}
return $options;
}
?>
<select>
<?php echo options(6); ?>
</select>
This function outputs the requested code.
You can create the selectbox using sprintf to make easier to organize the data.
<?php
function createSelectBox($arr){
$options= '<select>';
for($i=0; $i <= count($arr); $i++){
$options .= sprintf("<option value='%s'>%s</option>", $arr[$i]['ID'], $arr[$i]['title']);
}
$options .= '</select>';
return $options;
}
?>
I came a across this looking for a code fragment. I ended up writing a function its call and everything that goes with it (albeit here I've put the CSS inside style tags instead of a CSS file)
You can put this in and it'll work.
<?php
function createOptionBox($boxName,$boxClass ,$productArray){
$boxHtml = '<select name="'.$boxName.'" class="'.$boxClass.'">';
for($x=0;$x<count($productArray);$x+=2){
$boxHtml .= '<option value="'.$productArray[$x].'">'.$productArray[$x+1].'</option>';
}
$boxHtml .= '</select>';
return($boxHtml);
}
$productArray = array("1","ipad","2","phone");
$boxName = "products";
$boxClass = "productSelect";
$productDropDown = createOptionBox($boxName,$boxClass ,$productArray);
?>
<style>
.productSelect{
font-size:12pt;
padding: 5px;
}
</style>
<p><?php echo $productDropDown;?></p>
the productArray can easily be set up from a database - like mysql, by simply using array_push.
Hope this helps someone.
Related
I have a file which currently contains
C41234
B36355
B41234
and I can't seem to find a way to read these from the file and then add each to my dropdown. The contents of the file are subject to change so I need to use a variable of some sort. I'm using php to read my file. I took a shot in the dark and tried
$j= 0;
echo'<b>Choose the reservation you would like to change </b>';
echo'<p>';
echo'<select name="change">';
while (!feof($fp))
{
echo'<option> $reservations[$j]</option>';
$j++;
}
echo '</select>';
where $reservations[] already contains the file contents. it's echoing the html just fine, i'm just not filling the dropdown correctly.
any help is much appreciated!
$fp = fopen("reservations.txt", "r");
echo '<b>Choose the reservation you would like to change </b>';
echo '<p>';
echo '<select name="change">';
while(!feof($fp)){
$line = trim(fgets($fp));
echo "<option>{$line}</option>";
}
fclose($fp);
echo '</select>';
Hope this code helps you!
First thing you'll want to do is build your reservations array:
$reservations = file("my_reservations.txt");
http://php.net/manual/en/function.file.php
Then loop through that array and echo your options:
<select>
<?php
for ($i=0; $i < count($reservations); $i++) {
echo "<option>" . $reservations[$i] . "</option>";
}
?>
</select>
If $reservations already looks like this...
array(3) {
[0] =>
string(6) "C41234"
[1] =>
string(6) "B36355"
[2] =>
string(6) "B41234"
}
Then all you need to do is loop through the $reservations array...
foreach ($reservations as $res) {
echo "<option>$res</option>";
}
I have a section of php code where I need for the $_POST index to increment by one each time it goes through the "do while" loop. In other words, the first occurrence would be $_POST['tableserver1'], then the next one would be $_POST['tableserver2'], etc. This loops 6 times and then stops.
I have tried using variables as the index, trying to get them to increment. I found an example in the php manual http://php.net/manual/en/language.operators.increment.php which increments the number at the end of a string, but I'm not having any luck with getting it to work inside the $_POST index.
This section of code creates a set of 6 select lists that contain names from the database. I am trying to get the select lists to populate from the $_POST value if it is set, other wise it is zero.
Here is my code:
<?php
$x = 1;
do {
?>
<blockquote>
<p><?php echo $x . "."; ?>
<select name="tableserver<?php echo $x; ?>" id="tableserver<?php echo $x; ?>">
<option selected value="0" <?php
if (!(strcmp(0, '$tableserver.$x'))) {
echo "selected=\"selected\"";
}
?>>Select Server</option>
<?php
do {
if (strpos($row_getnamesRS['service'], '22') !== false) {
?>
<option value="<?php echo $row_getnamesRS['memberID'] ?>" <?php
if (!(strcmp($row_getnamesRS['memberID'], '$tableserver.$x'))) {
echo "selected=\"selected\"";
}
?>><?php
echo ucfirst(strtolower($row_getnamesRS['first_name']))
. " " . ucfirst(strtolower($row_getnamesRS['last_name']))
?></option>
<?php
}
} while ($row_getnamesRS = mysqli_fetch_assoc($getnamesRS));
$rows = mysqli_num_rows($getnamesRS);
if ($rows > 0) {
mysqli_data_seek($getnamesRS, 0);
$row_getnamesRS = mysqli_fetch_assoc($getnamesRS);
}
?>
</select>
</p>
</blockquote>
<?php
$x++;
} while ($x <= 6);
?>
$i=0;
do{
echo $_POST['someval'.$i];
}while(++$i < 6)
Perhaps like this? ...
$arr = [];
for ($i = 1; $i <= 6; $i++)
array_push($arr, $_POST["tableserver" . $i]);
$arr; // Contains 6 values (starting from $_POST["tableserver1"] to $_POST["tableserver6"])
It would be easier to post an an array
so instead of
name="tableserver<?php echo $x; ?>"
use
name="tableserver[]";
the you can just do
foreach($_POST['tableserver'] as $tableServer){....}
I have a dropdown section menu that I need to set the selected value based on the database values.
I have a table with the following structure: id, pid, disporder, title, url
I am then using this code for the dropdown:
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
echo "<option value=\"".$parent['id']."\">".$parent['title']."</option>";
}
echo "</select>";
How would I go by getting the selected value based on what's in the database?
I have multiple entries in the table, so using an array with values (similar to this), isn't what I want to use:
$options = array('1', '2', '3');
foreach($options as $option)
{
if($option = $parent['id'])
{
echo "selected";
}
else
{
echo "";
}
Thanks.
You haven't really given enough info to really say what the exact solution would be. If you're creating a select tag in PHP though, the typical pattern for building the markup is:
<?php
$options = get_me_some_options();
$select_markup = '<select name="my-select" id="my-select>';
foreach ($options as $key => $val) {
$selected = '';
if (is_this_selected($val)) {
$selected = 'selected';
}
$select_markup .= "<option $selected val=\""
. $val['id'] . "\">" . $val['name'] . '</option>';
}
echo $select_markup . "</select>";
It looks like your use case is similar, but slightly more complex. Ultimately though what matters is that, inside the loop, you have some way to determine whether a given row should be 'selected' or not.
If I understand correctly, you want to compare each $parent['id'] with the values of an array called $options. Try this:
$options = array('1', '2', '3');
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
$selected = ( in_array($parent['id'], $options) ? ' selected' : '';
echo "<option value=\"".$parent['id']."\"$selected>".$parent['title']."</option>";
}
echo "</select>";
If you're trying to use this in multiselects then this might help
<?php
$optionsToSelect=array(1,2,3);
?>
<select name="parent" id="parent">
<?php
foreach($allOptions as $opt){
?>
<option value="<?php echo $opt['value'];?>" <? echo $opt['selected']==1?'selected="selected"':'';?>><?php echo $opt['optTitle'];?><option>
<?php
}
?>
</select>
I`m using this code to repopulate drop down list from the database :
$city_id = 15;
while($row = mysql_fetch_assoc($result)) {
$selected = ($row['city_id'] == $city_id) ? 'selected="selected" ' : NULL;
echo '<option value="'.$city_id .$selected . '">"'.$row['city_name'].'"</option>\n';
}
It`s work like a charm but my question is are they more elegance solutions ?
Other than improving the indentation of the code, this is fine.
$city_id = 15;
while($row = mysql_fetch_assoc($result))
{
$selected = ($row['city_id'] == $city_id) ? ' selected="selected"' : NULL;
echo '<option value="' . $row['city_id']. '"' . $selected . '>'.$row['city_name'].'</option>\n';
}
Well, a more elegant solution would be to have a "controller" file that fetches all the cities an puts them into an array/object list/whatever. Then, in a "view" file, you iterate over that variable. That way, you separate a bit more the presentation from the logic.
In view:
<select name=student value=''>Student Name</option>
<?php foreach($cities as $city): ?>
<option value="<?php echo $city->id ?>" ><?php echo $city->name ?></option>
<?php endforeach; ?>
</select>
Also, I'd highly recommend using PDO for DB access.
I always use a function, since select boxes are something I end up creating a lot...
function select($name, $default, $values, $style='', $param='') {
$html = '<select name="'.$name.'" style="'.$style.'" '.$param.' >';
foreach($values as $i => $data) {
if (isset($data['noFormat'])) {
$html .= '<option value="'.$data['value'].'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.$data['text'].'</option>';
} else {
$html .= '<option value="'.htmlentities($data['value']).'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.htmlentities($data['text']).'</option>';
}
}
$html .= '</select>';
return $html;
}
Then loop through your query to build the array like this:
$default[] = array('value' => '0', 'text' => 'Select a City...');
while($row = mysql_fetch_assoc($result)) {
$list[] = array('value' => $row['city_id'], 'text' => $row['city_name']);
}
$list = array_merge($default,$list);
And finally an example to create the HTML:
select('select','form_el_name',$list['0'],$list,'font-size:12px;','onChange="document.forms[0].submit();"');
Hope it helps!
mysql_fetch_assoc to mysql_fetch_array
add proper comments
use standard php class ezsql or simple class tuts
$query="SELECT name,id FROM student";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[id]>$nt[name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";//Closing of list box
I would like to create nested divs dynamically, preferably without JavaScript.
So if you have n number of DIVs, DIV1 contains DIV1 which contains DIV3 etc…
How would I code that in PHP?
function recursiveDiv($num) {
$html = '<div id="div'.$num.'">%s</div>';
for($i = $num - 1; $i >= 1; $i--) {
$html = '<div id="div'.$i.'">'.$html.'</div>';
}
return $html;
}
echo sprintf(recursiveDiv(5), 'Hello World');
Untested but should give you want you want.
Here is a simple loop example using $n = 3. You can change $n to any number and it will nest div tags for you. I'm not entirely sure why you would want to do this, but here it is.
$openingTags = '';
$closingTags = '';
$n = 3;
for ($i = 0; $i < $n; ++$i) {
$openingTags .= '<div id="div' . $i . '">';
$closingTags .= '</div>';
}
echo $openingTags . 'Hello World' . $closingTags;
This code should allow you to create the nested divs and also populate them with content. Replaced orginal code with below, this should work but its untested
$result = mysql_query("SELECT * FROM table");
$count = mysql_num_rows($result);
$html = '';
$end_html = '';
while($row = mysql_fetch_object($result)){
$html .= '<div id="div'.$count.'">'.$row->textfield; # any database column
$end_html .= '</div>';
$count--;
}
echo $html . $end_html;
While others are suggesting using mathematical solutions based on for loops, you can do this a bit more explicitly—clearly setting classnames—by using an array like this:
// Set the DIVs array.
$divs_array = array();
$divs_array[] = 'DIV1';
$divs_array[] = 'DIV2';
$divs_array[] = 'DIV3';
Now with that array set, you can use implode to take the content of those arrays and set them as DIV class values like this. Note the implode logic might seem confusing, but look at what it creates and look at how the code is set and it makes more sense after a while:
// Set the DIVs.
$div_opening = $div_closing = '';
if (!empty($divs_array)) {
$div_opening = '<div class="' . implode($divs_array, '">' . "\n" . '<div class="') . '">';
$div_closing = '</div><!-- .' . implode(array_reverse($divs_array), '-->' . "\n" . '</div><!-- .') . ' -->';
}
And then you can set the content between the $div_opening and $div_closing values like this:
// Return the content wrapped in the DIVs.
echo $div_opening
. '<p>Hello world.</p>'
. $div_closing
;
The output would be something like this:
<div class="DIV1">
<div class="DIV2">
<div class="DIV3">
<p>Hello world.</p>
</div><!-- .DIV3 -->
</div><!-- .DIV2 -->
</div><!-- .DIV1 -->
Note my personal coding style is to—whenever possible—set comments after each DIV that clearly shows what that </div> is actually closing. So that is what the comments like <!-- .DIV3 --> refer to; feel free to adjust to fit your own coding needs and style.