Getting my $_POST select option selected on submit - php

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

Related

PHP retrieve previous value after form submision inside loop

How can I retrieve selected value after form submision inside looped HTML select? I managed to solve the problem with manual if statements, but thats not dynamic.
I'm also storing previously submited value inside a cookie. I use self page form submit.
I managed to retrieve previous value from radio button:
<input type="radio" name="spol" value="moški" checked="checked" <?php if (isset($_POST['spol']) && $_POST['spol'] == 'moški') {
echo ' checked="checked"';
} ?>>
But can't find a way to do this inside foreach loop
<!---Cookie "keks" is storing previous submited string-->
<select name="status">
<?php
$_COOKIE['keks'];
$statusi = ["Dijak", "Študent", "Zaposlen", "Brezposelni"];
$counter= 0;
foreach ($statusi as $status) {
$counter++;
if ($counter == 2) {
echo "<option value=" . $status . " selected>" . $status . "</option>";
} else {
echo "<option value=" . $status . ">" . $status . "</option>";
}
}
?>
</select>
As stated in html comment, $_COOKIE['keks']; is storing the last value.
You might want to store that value into a variable or use it as is. and then, compare it against the current iteration of your loop.
$lastValue = $_COOKIE['keks'];
// some code
foreach ($statusi as $status)
{
if ($status == $lastValue)
// mark the option as selected
else
// don't mark it
}

Using random variables inside Arrays

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

How to use if and declare variable in echo statement php

I have a condition within echo statement like this, how to adjust it to make it working:
echo "<option value="http://localhost/myproject/index.php?if(empty($_GET['view'])){echo "view=main-content";}else{$view=basename($_GET['view']);echo "view=".$view;}"></option>";
Many thanks
I noticed that you are using two times view, threfore if you condition enters the else your final url would be something like: ?view=whateverview=whatever2 which is clearly wrong.
$view = (empty($_GET['view']) ? 'main-content' : basename($_GET['view']));
echo "<option value='http://localhost/myproject/index.php?view=" . $view . "'></option>";
If you would like to add more parameters to the URL you'll need to use &.
is this your expected output?
$d = "<option value='http://localhost/myproject/index.php?";
if(empty($_GET['view']))
{
$d .= "view=main-content";
}
else
{
$view=basename($_GET['view']);
$d .="view=".$view;
};
$d .="'>Testing</option>";
echo "<select>". $d."</select>";
You could pass it to a variable, and concatenate it with the rest of your echo statement.
if(empty($_GET['view'])){
$res = 'main-content';
} else {
$res = basename($_GET['view']);
}
echo '<option value="http://localhost/myproject/index.php?view=' . $res . '"></option>';
And since no one else posted it:
echo '<option value="http://localhost/myproject/index.php?view='
. (empty($_GET['view']) ? 'main-content' : basename($_GET['view'])
. '"></option>';

Sticky forms in php

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

selected option in select dissappears on reload

Once it loads in my page, if nothing has been saved in the DB table, all options are shown. As soon as i make a selection and reload the page, the selected option dissapears from the list and isn`t reloaded in the dropdown. Instead, it displays the next value which takes the place of the selected one.
if i check the SQL statement and the $str, it does load all the options except the one which is selected which is in $getBris (it has a value).
What could be causing my select to not display my selected option and instead removing it from the list?
*It specifically doesnt work in IE8, wasnt working in Firefox but now it does
<script src="validation.js" type="text/javascript"></script>
<html>
<body onLoad="checkSecondValue();">
</body>
</html>
<?php
//retrieve all the bris for the drop down
include '../../inc/database.php';
// ORDER BY RAND()
$res = BbqcDatabase::getInstance()->doQuery('SELECT * FROM T_TOURNOI_BRIS');
$str = "<select name='ddlBrisSelected' id='ddlBrisSelected' onChange='checkSecondValue()'>";
$getBris = $_GET['bris'];
$getBris = $getBris - 1;
print_r("bris is : "+ $getBris);
if($getBris == null)
{
$str .= "<option value='' selected></option>";
}
else
{
$str .= "<option value='999'>Choisir un bris</option>";
}
$i = 0;
while($data = mysql_fetch_assoc($res))
{
if($data['F_BRISID'] == $getBris)
{
$str .= "<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>";
}
else
{
$str .= "<option value='" . $data['F_BRISID'] . "'>" . $data['F_BRISTITLE'] . "</option>";
}
$i++;
}
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
$str .= "</select>";
echo $str;
if(is_numeric($bris))
{
echo "<script type=\"text/javascript\">alert('test');checkSecondValue();</script>";
}
?>
Use your browser's View Source feature to inspect the actual HTML you are generating (which is, in fact, the only see the browser ever sees). It looks like you're inserting random single quotes.
Update:
<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>"
... will render as:
<option value='blah' selected '>blah</option>
It's the only error I've cared to spot but an HTML validator should find them all. Also, I recommend you use this syntax:
<option value="blah" selected="selected">blah</option>
A construct like this
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
is highly wasteful of space and forces you to duplicate a big chunk of html whose only difference is the "selected" attribute. Why not do something like this:
$selected = ($getBris == 12) ? ' selected' : '';
$str .= "<option value=12{$selected}>Autre</option>";

Categories