PHP get value from Drop down list - php

PHP get dropdown value and text
Hi I was following this post in the link above to get the users selected option from the drop down list and to do something depending on which is selected. I have a input box for the user to type a message and a drop down list of colors and if the user clicks on a certain color, it will take the users message and change it to that color but can't seem to work.
<select name="color" id="color">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
Here is the post
if($_POST['red'] = 'red' )
{
echo "<font color ='red'> Hi $name </font><br />";
} elseif ($_POST['submit'] = 'green')
{
echo "<font color ='green'> Hi $name </font><br />";
} elseif ($_POST['submit'] = 'blue')
{
echo "<font color ='blue'> Hi $name </font><br />";
}
All it does is make the font color red, no matter which drop down option was selected. I tried a variety of different things but can't seem to figure this out.

Take a look at the field you're POSTing:
<select name="color" id="color">
...
</select>
When accessing the $_POST array, you're not looking for the value that gets posted, you're looking for the field, which is, in this case, color, not red, green or blue.
You've got the right idea, but your if statement is looking for the wrong thing, and using the wrong = (should be == for comparison):
if($_POST['color'] == 'red'){
echo "<span style='color:red;'>Hi ".$name."</span>";
} else if ($_POST['color'] == 'blue'){
echo "<span style='color:blue;'>Hi ".$name."</span>";
} else if ($_POST['color'] == 'green'){
echo "<span style='color:green;'>Hi ".$name."</span>";
}
Fix those errors and your code should work. Also, look into using an IDE, which would show you these errors (especially the = vs == one).

You need to use the right variable in the array.
You also need to compare == and not assign =
if($_POST['color'] == 'red' ) {
echo "<font color ='red'> Hi $name </font><br />";
} elseif ($_POST['color'] == 'green') {
echo "<font color ='green'> Hi $name </font><br />";
} elseif ($_POST['color'] == 'blue') {
echo "<font color ='blue'> Hi $name </font><br />";
}
Or, as I would do it:
No if at all, just echo our the color.
echo "<font color='".$_POST['color']."'> Hi ".$name." </font><br />";
You can also try it as a switch statement:
switch($_POST['color']){
case "red":
echo "<font color='red'> Hi ".$name." </font><br />";
break;
case "blue":
echo "<font color='blue'> Hi ".$name." </font><br />";
break;
case "green":
echo "<font color='green'> Hi ".$name." </font><br />";
break;
default:
echo "Hi ".$name."<br />";
break;
}
You probably want to escape strings and such first. But that gives you an idea.

Change first line to:
if($_POST['color'] == 'red' )

Related

PHP form is returning before if statement completes

I have a bit of code in which I want a form to appear when the New Player button is clicked. My problem is when I click on the submit button in the form, the validation code does not run. I'm not sure how to force the function to retain control.
The original New Player button calls an external PHP script
echo "<form action = '', method = 'post'>";
echo "<button name = 'showPF', type = 'submit', value = 'New Player'>New Player</button></br>";
echo "</form>";
if(isset( $_POST['showPF'])) {
require(__DIR__.'/new_player.php');
}
The form is then shown and in turn calls a function. This function is the part that never gets executed.
echo "<form action = '' method='post'>";
echo "Player Name: <input type='text' name='playerName'></br>";
echo "Character Name: <input type='text' name ='charName'></br>";
echo "Class: <input type='text' name = 'class'></br>";
echo "Race: <input type='text' name = 'race'></br>";
echo "Level: <input type = 'int' name = 'level'></br>";
echo "<button name='add', type = 'submit', value = 'Add Player'>Add Player</button></br>";
echo "</form>";
if(isset($_POST['add'])){
addPlayer();
}
The addPlayer() function looks like
function addPlayer(){
//PLAYER NAME
if(empty($_POST['playerName'])){
//Player Name is required
echo "Player Name is required";
}
elseif(ctype_alpha(str_replace(' ','', $_POST['playerName'])) == FALSE){
//Player Name can only be letters and spaces
echo "Player Name can only contain letters and spaces";
}
else{
$playerName = $_POST['playerName'];
}
//CHARACTER NAME
if(empty($_POST['charName'])){
$charName = "NULL";
}
elseif(ctype_alpha(str_replace(' ','', $_POST['charName'])) == FALSE){
//Character Name can only be letters and spaces
echo "Character Name can only contain letters and spaces";
}
else{
$charName = $_POST['charName'];
}
//CLASS
if(empty($_POST['class'])){
$charClass = "NULL";
}
elseif(ctype_alpha(str_replace(' ','', $_POST['class'])) == FALSE){
//Class can only be letters and spaces
echo "Class can only contain letters and spaces";
}
else{
$charClass = $_POST['class'];
}
//RACE
if(empty($_POST['race'])){
$charRace = "NULL";
}
if(ctype_alpha(str_replace(' ','', $_POST['race'])) == FALSE){
//Race can only be letters and spaces
echo "Race can only contain letters and spaces";
}
else{
$charRace= $_POST['race'];
}
//LEVEL
if(empty($_POST['level'])){
$charLvl = "NULL";
}
if(ctype_digit($_POST['level']) == FALSE){
//Level must be a number
echo "Level must be a number";
}
else{
$charLvl= (int)$_POST['lvl'];
}
}
Since I don't know why it's not completing the second if statement I'm not sure how to google my answer. And, I know my code isn't pretty. I'm relearning after 10+ years out of school. Unfortunately, I don't know where else to ask such a novice question.
Thank you for your time.
The problem is that new_player.php is included only when you submit the showPF value, but the second form doesn't have such field. As a solution, just add a hidden field for your second form:
<input type='hidden' name='showPF' value='New Player'>

How to display php script output in column wise based on the match in if statement

I have the following PHP code which will print the server names with different color codes likes Green-Ok,Yellow-warning,Red-critical,Orange-unknown.
foreach ($status->members_with_state as $server) {
if ($server[1] == 0) {
$state = "OK";
echo "Server: <font color=\"green\">$server[0]</font><br />";
} elseif ($server[1] == 2) {
$state = "WARNING";
echo "Server: <font color=\"yellow\">$server[0]</font><br />";
} elseif ($server[1] == 1) {
$state = "CRITICAL";
echo "Server: <font color=\"red\">$server[0]</font><br />";
} elseif ($server[1] == 3) {
$state = "UNKNOWN";
echo "Server: <font color=\"orange\">$server[0]</font><br />";
}
}
ISSUE:
All the servers are printed in one big list in a single column.
Could you please suggest required modifications in code to get the server names column wise like in attached screenshotenter image description here

is this possible for radio button? or I misunderstood what he wants

I'm told to do this
If the user has entered both names and checked a radio button, show a greeting Hello <firstname> <lastname>. Change the background color of the Web page to the selected color. You do this by using the echo statement as follows:
echo "<body bgcolor =\” $color\”> Hello $firstname $lastname";
and my other php file I have
elseif(!(empty($_GET["fname"])) && (!(empty($_GET["lname"]))) && ($_GET["bgcolor"] == "red"))
{
echo "<body bgcolor='red'>" . "Hello " . $_GET["fname"] . " ". $_GET["lname"] . "!<br/>" . "Background color changed to the selected color";
}
is it possible if I put the the $_GET["bgcolor"]'s value into the <body bgcolor=''>? so I don't have to use another elseif statement...
because seeing this
echo "<body bgcolor =\” $color\”> Hello $firstname $lastname";
lets me think it's possible but if with just one variable $color how is that possible O.o
Well, sure it is. But why didn't you try that out yourself ? Would have taken less time than to post this question. :)
For example something like this:
$default_color = "white";
[...]
if(!(empty($_GET["fname"])) && (!(empty($_GET["lname"])) && (!(empty($_GET["bgcolor"])))
{
echo "<body bgcolor=". $_GET["bgcolor"] .">" . "Hello " . $_GET["fname"] . " ". $_GET["lname"] . "!<br/>" . "Background color changed to the selected color";
}
else
{
echo "<body bgcolor=". $default_color .">" . "Hello " . $_GET["fname"] . " ". $_GET["lname"] . "!<br/>" . "Background color changed to the default color";
}
Use something like this
<input type="hidden" value="your-color" name="bgcolor"/>
if($_GET["bgcolor"] == 'color'){
$color = 'color'
}else {
$color = 'other color'
}
echo '<body bgcolor='.$color.'>';
Assuming you have one radio button per available color you can do this by saving the color in the value attribute of the radio button. This value will be passed on POST.
<input type="radio" value="red" name="bgcolor"/>
results in
$_POST["bgcolor"] === "red"

PHP: Displaying a value dependent on input

In my view I have the following select menu that states what type of form types are available:
<label for="add_fields_type">Type: </label>
<select name="add_fields_type" id="add_fields_type">
<option value="input">Input</option>
<option value="textarea">Text Area</option>
<option value="radiobutton">Radio Button</option>
<option value="checkbox">Check Box</option>
</select>
In my controller I currently have the following but I am unsure how to make is so that if $_REQUEST['add_fields_type'] is = to lets say radiobutton then it will display that respective code.
Controller:
if (isset($_REQUEST['add_fields_type']))
{
echo $_REQUEST['add_fields_type'];
}
if (isset($_REQUEST['add_fields_type'])) {
if ($_REQUEST['add_fields_type'] == 'input') {
// echo stuff for input
}
else if ($_REQUEST['add_fields_type'] == 'textarea') {
// echo stuff for textarea
}
else if ($_REQUEST['add_fields_type'] == 'radiobutton') {
// echo stuff for radiobutton
}
else if ($_REQUEST['add_fields_type'] == 'checkbox') {
// echo stuff for checkbox
}
}
Another way, using the switch code that swapnesh mentioned (slightly more concise than having multiple if statements and will stop when it hits the right case):
if (isset($_REQUEST['add_fields_type']))
{
switch($_REQUEST['add_fields_type'])
{
case('input'):
// echo stuff for input
break;
case('textarea'):
// echo stuff for textarea
break;
case('radiobutton'):
// echo stuff for radiobutton
break;
case('checkbox'):
// echo stuff for checkbox
break;
default:
// echo stuff if the other cases fall through
break;
}
}

Calling and Declaring a select box in PHP!

I want to be able to change the color of my websites background depending on which option the user chooses.
I have this code for my select box:
<select name="change_date" >
<option value="1" id="1">1</option>
<option value="2" id="2">2</option>
<option value="3" id="3">3</option>
</select>
Using PHP, how would i get it so that it simply changed to red for 1, green for 2 and pink for 3?
This is the code I have tried (unsuccessfully and complete guesswork):
<?php
if(isset($_POST['change_date'])=='1' )
{
echo "<body style='background-color:red;'></body>";
}else{
echo "failed";
}
if(isset($_POST['change_date'])=='2' )
{
echo "<body style='background-color:green;'></body>";
}else{
echo "failed";
}
if(isset($_POST['change_date'])=='3' )
{
echo "<body style='background-color:pink;'></body>";
}else{
echo "failed";
}
?>
Any suggestions? methods? links?
UPDATE:
I have tried all methods and none seem to work guys. It must be something I am doing wrong.
What i want is when the user chooses and option ie 1,2 or 3 and clicks send, then the color will change.
Hope this helps more. I forgot to add before that I want a send button to have to be clicked then all the clever stuff happens.
Thanks
if (isset($_POST['change_date']))
{
switch ($_POST['change_date'])
{
case 1: $color = 'red'; break;
case 2: $color = 'green'; break;
case 3: $color = 'pink'; break;
default: die('failed');
}
echo "<body style='background-color:$color;'></body>";
}
Use a switch:
$color = !empty($_POST['change_date'])?$_POST['change_date']:0;
switch ($color) {
default:
case 1:
echo "pink";
break;
case 2:
echo "orange";
break;
}
Should do what you want. Plenty of other ways to do it with arrays etc. Just the way I chose to show you :)
EDIT:
Array Method
$colors = array(1 => 'pink', 2 => 'orange');
$color = !empty($_POST['change_date'])?$_POST['change_date']:1;
echo "<body style='background-color:" . $colors[$color] . ";'></body>";
Both should work, pending any errors I made.
your PHP code only works if the variable "change_date" comes from a query string via a POST method...
Do you need to set the color on the fly? or after sending a form?
You're problem is in your use of isset. This function simple returns a boolean value, not the value of the field. Try the below:
if(isset($_POST['change_date']))
{
switch($_POST['change_date'])
{
case 1:
echo "<body style='background-color:red;'></body>";
break;
case 2:
echo "<body style='background-color:green;'></body>";
break;
case 3:
echo "<body style='background-color:pink;'></body>";
break;
default:
echo "<body style='background-color:white;'></body>";
}
}
else
{
echo "<body style='background-color:white;'></body>";
}
Another way could be, if you dont wanna use switch statement ,
$color = isset($_POST['change_date']))?$_POST['change_date']:0;
if($color){
if($color == 1) echo "<body style='background-color:red;'></body>";
if($color == 2) echo "<body style='background-color:green;'></body>";
if($color == 3) echo "<body style='background-color:pink;'></body>";
}
Try a value map array, and as pointed out in one of the other answers it might be GET instead of POST, so I'm using $_REQUEST as example:
<?php
$colors = array(
1 => "red",
2 => "green",
3 => "pink",
);
if ($c = $colors[ $_REQUEST["change_date"] ])
{
echo "<body style='background-color: $c;'>body</body>";
}
else {
echo "failed";
}

Categories