My code:
<label>Year: </label>
<?php
print '<select>';
$start_year = date('1910');
for ($y = $start_year; $y <= ($start_year + 104); $y++) {
print "<option value=\"$y\">$y</option>";
}
print '</select>';
?>
and our professor wants us to incorporate it being sticky with something like a code like this:
echo "<option value=\"$option\"";
if ($messageType == $option){
//make it sticky
echo ' selected="selected"';
}
echo ">$option</option>";
however that code isn't working with my code and i can't seem for it to become a default value/sticky.
In your for loop:
for ($y = $start_year; $y <= ($start_year + 104); $y++) {
($y== $option) ? echo '<option value="'.$y.'" selected="selected">'.$y.'</option>' : echo '<option value="'.$y.'">'.$y.'</option>';
}
I assumed that the value of $option is a year available in your for loop.
I hate to post an entire answer for this but i cannot comment yet... Given your problem "can't seem for it to become a default value" My money on its a very simple issue
echo ' selected="selected"';
should just be
echo ' selected';
http://www.w3schools.com/tags/att_option_selected.asp
but view source on the webpage it generates and make sure the HTML is generating as expected otherwise
Related
First of all, sorry if this is worded poorly, as I'm a beginner at code.
I'm currently working on an online computer science course, however I'm quite confused on how to do one small part. We need to use arrays for this activity, where the user has multiple selections and each different selection has a different/unique text output. Everything works fine, except I need an option to choose a random selection, however I'm a bit confused on how to make it. You can see from my code the options 1-8. I want it to randomly select one of the selections.
Here's my code:
<?php
$train[0] = "Canada";
$train[1] = "Sahara Desert";
$train[2] = "Russia";
$train[3] = "Chernobyl";
$train[4] = "United States";
$train[5] = "North Korea";
$train[6] = "Germany";
$train[7] = "Hawaii";
?>
<!DOCTYPE html>
<html>
<head>
Took out everything here, it's not important.
</head>
<body>
<center>
<h1>Vacation Time!</h1>
<h4>You and your family just won the lottery! You all want to go on vacation, but nobody can agree where to go. Inside each train cart has a card with a location written on it. Whatever you find is where you're going! </h4>
<form name="form1" action="activity-2-7-arrays-a.php" method="post">
<label>Which cart on the train do you want to choose?</label>
<br>
<select name="cart" required>
<option value="1">First Cart</option>
<option value="2">Second Cart</option>
<option value="3">Third Cart</option>
<option value="4">Fourth Cart</option>
<option value="5">Fifth Cart</option>
<option value="6">Sixth Cart</option>
<option value="7">Seventh Cart</option>
<option value="8">Eight Cart</option>
<option value="show">Show all options</option>
<option value="any">Choose Randomly</option>
<br>
</select><br/>
<input type="submit" name="subButton" class="subButton" value="Go!"/><br/>
</form>
<h1><u>Final Results</u></h1>
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
$roll = rand(1,9);
if($cart == show) {
for($x = 1; $x <= 9; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
}
return;
}
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
return;
if ($cart == $roll) {
}
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll] . "! Have fun! </h2>";
?>
I'm sure it's a bit messy, also. Hopefully you understand what I mean. If you're able to explain the answer to me that would be extremely helpful. Thank you :)
You are randomly generating a value regardless of the user choice and comparing it with user's selection and other weird things.
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
$roll = rand(1,9);
You are generating a random value before even checking if user selected 'Choose randomly' and why generate a random between 1 and 9? Your $train array starts with index 0 and ends with index 7.
if($cart == show) {
String needs to be quoted.
for($x = 1; $x <= 9; $x++) {
Again looping $x from 1 to 9 makes no sense because of your array indexes.
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
Will fail when $x reaches 8 since last index in $train is 7.
}
return;
}
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
return;
So if user didn't select 'Show all options' you show him his chosen location. If user chose 'Select Randomly' this will fail since $cart would have value 'any' and $train['any'] does not exist.
Here is code with correct logic.
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
if ($cart == 'any') {// Check if user selected 'Choose Randomly'
$roll = rand(0, 7);
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll] . "! Have fun! </h2>";
}
else {
if ($cart == 'show') { // If user selected 'Show all options'
echo "<p> You could have ender up in... </p>";
for($x = 0; $x <= 7; $x++) {
echo "<h2> " . $train[$x] . "</h2>";
}
}
else { // User selected cart so show him chosen location
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
}
}
?>
Here is some problems in the code
from where and why we return?
no closing html-tags
I would change the last part of php-code like that:
<?php
if ($_POST['subButton']) {
$cart = $_POST['cart'];
$value = intval($cart);
$roll = mt_rand(1, 8); // mt_rand() has more entropy than rand()
if ($cart == 'show') {
// show target locations (according the OP-source)
for($x = 1; $x <= 8; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x-1] . "</h2>";
}
} else if ($value > 0 && $value <= 8) {
echo "<h2>"."Well, it looks like you're going to " . $train[$value-1] . "! Have fun! </h2>";
// idk why it needed, but move it here
if ($value == $roll) {
}
} else if ($cart == 'any') {
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll-1] . "! Have fun! </h2>";
} else {
// $_POST['cart'] has something wrong
}
}
?>
<!-- lines below was added to close html-tags -->
</body>
</html>
What you're looking for is array_rand():
$random = array_rand($train);
Instead of rand() use mt_rand() because the PHP DOCUMENTATION literally says
mt_rand — Generate a better random value
Regarding your php code, you have a lot of errors. This is how your bottom php code should look:
<?php
if($_POST['subButton'])
{
$cart = $_POST['cart'];
$roll = mt_rand(0,7);
//0-7 because those are the values you inserted into
//the $train[] array
if($cart == 'show') {
//another correction here, it has to be 0-7
for($x = 0; $x <= 7; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
}
}
else if ($cart!='any')
{
"<h2>Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
else //took out return and placed an else
{
echo "<h2>Well, it looks like you're going
to " . $train[$cart] . "! Have fun! </h2>";
}
?>
when i click the edit button it should go the edit page
when i want to edit the row with coursename="php" in the drop down the course name should have selected as php since the course name and the paper name,paper description are present in the different table i cant select the particular value in drop down
if(isset($_GET['id'])) {
$table="papers";
$condition="paper_id=".$_GET["id"]."";
$select=selectlist($table,$condition);
$row=$list->fetch_array();
$table="courses";
$datalist=selectdata($table);
$data=Selectdata($table);
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
}
}
?>
i have tried the above code i know the problem is with the "selected" please help me
You are almost close to the answer.
Some modifications and you are done.
You need to compare two values.
The value from database (selected value) and the value in loop.
Another suggestion is that we should not write any logic inside any
HTML tag.
HTMLs/Templates are just for printing output to screen.
We should first evaluate all conditions and then print HTML.
selected Reference
Change
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
To:
$selected = ($row1['course_id'] == $courseid) ? 'selected="selected"' : '';
echo '<option value="'. $row1['course_id'].'" ' . $selected . '>'.$row1['course_name'].'</option>';
Replace your while loop:
<?php
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
if($courseid == $row1['course_id']) {
echo '<option value="'. $row1['course_id'].'" selected>'.$row1['course_name'].'</option>';
} else {
echo '<option value="'. $row1['course_id'].'" >'.$row1['course_name'].'</option>';
}
}
?>
You can do it as following:
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
$selected="";
if($row['course_id']==$course_id)
{
$selected="selected";
}
echo '<option value="'. $row1['course_id'].'" $selected>'.$row1['course_name'].'</option>';
}
This makes your job done
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
echo "<option value = '{$row1['course_id']}'";
if ($courseid == $row1['course_id'])
echo "selected = 'selected'";
echo ">{$row1['course_name']}</option>";
}
Try this (use ternary operator inside option)
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
change into
<option value="<?= $row1['course_id'] ?>" <?= $row1['course_id']==$courseid? "selected":""?> > <?= $row1['course_name'] ?> </option>';
This is part of a survey, where I´m having trouble with my date option. I have tested, that the value actually gets saved into the $_POST array when i submit, but i can't get it to preselect that value once it´s submitted. Hope someone can help me.
<pre>
$day=’’;
if (isset($_POST['submit']))
{
if(isset($_POST['day']))
{
$day = $_POST['day'];
}
$dayhtml='<select name="day">';
for($i=1;$i<=31;$i++)
{
if($day==$i)
{
$dayhtml.="<option value='$i' selected>$i</option>";
}
else
{
$dayhtml.="<option value='$i'>$i</option>";
}
}
$dayhtml.='</select>';
echo $dayhtml;
</pre>
This works for me, it seems that you have a missing closing brace for the if (isset($_POST['submit']) { } block which might be causing issues. Using $day=0 helps clarify the code as well.
Also better to put your strings in single quotes
$day=0;
if (isset($_POST['submit']))
{
if(isset($_POST['day']))
{
$day = $_POST['day'];
}
} # <!-- missing closing brace
$dayhtml='<select name="day">';
for($i=1;$i<=31;$i++)
{
if($day==$i)
{
$dayhtml.= '<option value="'.$i.'" selected>'.$i.'</option>';
}
else
{
$dayhtml.='<option value="'.$i.'">'.$i.'</option>';
}
}
$dayhtml.='</select>';
echo $dayhtml;
Try echoing $day first and check if its value is coming as 01 or 1 or 02 or 2 and you are comparing with 1 and 2 etc.
If this is not the case then cast $i into string as $i is numeric and what is coming in $_POST['day'] is string. Though php is loosely coupled but sometimes it creates a problem.
Also it will be good if you put code for day also. How are have taken input for day.
Your code does work after adding in the missing brace which should be just before this line:
$dayhtml='<select name="day">';
Please post all of your html and make sure that your submit button has the name 'submit'.
The below works just fine for me:
$day = 0;
if(isset($_POST['day']))
$day = $_POST['day'];
$dayhtml='<form method="post"><select name="day">';
for($i=1;$i<=31;$i++)
{
$selected = ($day == $i) ? 'selected' : '';
$dayhtml.= '<option value="'.$i.'" '.$selected.'>'.$i.'</option>';
}
$dayhtml.='</select><input type="submit" /></form>';
echo $dayhtml;
replace your $day=’’; with $day=0..
and your problem will be solved. I checked it on my pc...
the commas you used are not proper...
You've syntax errors, try with following code:
$day=''; // take a look here, '' instead ``
if (isset($_POST['submit']))
{
if( isset($_POST['day']) )
{
$day = $_POST['day'];
}
$dayhtml='<select name="day">';
for($i=1;$i<=31;$i++)
{
if($day==$i) {
$dayhtml.='<option value="' . $i . '" selected="selected">' . $i . '</option>';
}
else
{
$dayhtml.='<option value="' . $i . '">' . $i . '</option>';
}
}
$dayhtml.='</select>';
echo $dayhtml;
} // missing `}` here
NOTE: When you are writing html code in php it is a good practice to wrap attributes in double quotes instead of single ones
Firstly apologies for asking this as it is quite basic but
I just can't seem to get it right. Have searched on here and
elsewhere for an answer (and tried various) but there is always
an error. Spent too long on this little bit and should really know
the answer but here goes:
Ok I have a main php file using an include statement to bring in a drop down menu
with the options being populated from a MySQL database. In the file being included I have this while loop which creates the
options and works fine:
while ($db_field = mysql_fetch_assoc($result)) {
$ManList2 = $db_field['categoryName'];
echo '<option value="' . $ManList2 . '">' . $ManList2 . '</option>';
}
What I want to add is something like the following in the option tag:
if($search == '$ManList2') { echo 'selected'; }
I just can't seem to get it right in the echo statement.
Any help greatly appreciated.
echo '<option value="'.$ManList2.'" '.($search == $ManList2 ? 'selected' : '').'>'.$ManList2.'</option>';
How about something like this:
while ($db_field = mysql_fetch_assoc($result)) {
$ManList2 = $db_field['categoryName'];
echo '<option value="' . $ManList2 . '"';
if($search == '$ManList2') {
echo ' selected';
}
echo '>' . $ManList2 . '</option>';
}
echo "<option value='".$ManList2; if($search == '$ManList2'){ echo 'selected'; } echo "'>".$ManList2."</option>";
You may try something like this (Assumed your select's name is search)
$search = isset($_POST['search']) ? $_POST['search'] : ''; // or $_GET maybe
$selected = '';
while ( $db_field = mysql_fetch_assoc($result) ) {
$ManList2 = $db_field['categoryName'];
$selected = $search == $ManList2 ? 'selected' : '';
echo '<option '.$selected.' value="'.$ManList2.'">'.$ManList2.'</option>';
}
You could use variables to put into your PHP, like:
while($db_field = mysql_fetch_assoc($result)) {
$ManList2 = $db_field['categoryName'];
$selected = $search === $ManList2 ? "selected='selected'" : '';
echo "<option value='$ManList2'$selected>$ManList2</option>";
}
I don't see what $search does, so this approach may not work. I would use my PHPglue Library. It handles this sort of thing for you.
I have the code to select the values from a database for populating my drop down list. But my question is if I stored the value of what the user selected in another database, how would I go about pulling that back out and making that the selected choice.
<select name="dropdown1" id="dropdown1">
<?php
for ($i = 0; $i < 5; $i++)
{
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
}
?>
</select>
So the users stored value is lets say red. How would I make red the selected value as it populates my drop down list?
Thanks e
<select name="dropdown1" id="dropdown1">
<?php
$selected = "red";
for ($i = 0; $i < 5; $i++)
{
if ($options[$i]['Value'] == $selected) {
print '<option selected="selected" id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
} else {
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
}
}
?>
</select>
On each element test the value. If the value is selected, print 'selected'.
<select name="dropdown1" id="dropdown1">
<?php
$selected = 'red';// obviously replace with DB value.
for ($i = 0; $i < 5; $i++)
{
// start as normal
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'"';
// if this one is selected, add 'selected' to the tag.
// NOTE: booleans in HTML do not need to have an attribute value.
// so selected="selected" is not necessary here.
if( $options[$i]["Value"] == $selected ) print ' selected';
// finish as normal
print '>'.$options[$i]["Name"].'</option>'."\n";
}
?>
</select>
As a side note: if you use foreach it will make for smaller, more compact, and often faster code:
//this assumes that you want to iterate the whole options array
foreach( $options as $option )
{
print '<option id="'.$option["ID"].'" value="'.$option["Value"].'"';
if( $option["Value"] == $selected ) print ' selected';
print '>'.$option["Name"].'</option>'."\n";
}