This is rather simple: I still have some problems to create good, conclusive questions but i try my best.
I want to create a php Code that progresses while the user is submitting the information with some radio buttons. There is a script example i wrote so far.
Every Time the user clicks a radio button and submits the content the code should progress and $count gets a + 1. So far i created two steps of progression. Everytime the user chose one radio button and clicks the submit button the program should echo something else insteat what it does right now is it echos everything of the chosen radiobutton in one step. (what i don't want to have)
I don't know why that is so. Shouldn't break in Case stop the code and restart it?
I used CASE for this and i am pretty sure that is not the best way, if it is a way at all because it does not work. I think every time the user clicks the submit button the whole code resets instead of that the progression is saved.
What do i have to do? Do i have to use arrays to save the clicked information or do i have to use LOOPS? I tried around with both but i still have no solution for my problem.
What would be the simplest solution for the code i have in mind? One step further i want to create a simple text adventure with php. I have to learn PHP for a Test and i think to play around with the code a little will help me to understand how it works.
Here is the code i wrote but i think i have to rearrange it and to use other things istead of case to make it work.
<html>
<head>
<title>Abfrage</title>
</head>
<body>
<h4> Typentest</h4>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>"method="post">
<p>What would you chose?</p><br />
<input type="radio" id="a1" name="weapon" value="1" checked> <label for="a1"> Dagger</label><br>
<input type="radio" id="a2" name="weapon" value="2"> <label for="a2"> Sword</label><br>
<input type="radio" id="a3" name="weapon" value="3"> <label for="a3"> Saber</label><br>
<input type="submit" name="gesendet" value="ok"></button> <br />
</form>
<?php
if(isset($_POST['gesendet'])){
// Variablen deklararien und Werte zuweisen.
$weapon = $_POST['weapon'];
$count = 0;
//First chosing
if (!empty($weapon) && $count == 0){
switch($weapon){
case "1":
echo "You chose a crude dagger ";
$count = $count + 1;
break;
case "2":
echo "You chose a crude sword";
$count = $count + 1;
break;
case "3":
echo "you chose a crude saber";
$count = $count + 1;
break;
}
}
//second chosing after second time "submit"
if (!empty($alter) && $count == 1){
switch($alter){
case "1":
echo "you chose a fine dagger";
$count = $count + 1;
break;
case "2":
echo "you chose a fine sword";
$count = $count + 1;
break;
case "3":
echo "you chose a fine saber";
$count = $count + 1;
break;
}
}
else {
echo "Ihre Eingabe ist fehlerhaft ";
}
}
?>
</body>
Nope,
If I understand well, you want something like that (by registering your steps in the form $_POST['count']):
$count = 0;
if(isset($_POST['gesendet'])){
// Variablen deklararien und Werte zuweisen.
$alter = $_POST['alter'];
$count = $_POST['count'];
if (!empty($alter) {
if($count == 0){
switch($alter){
case "1":
echo " a";
$count = 1;
break;
case "2":
echo "b";
$count = 1;
break;
case "3":
echo "c";
$count = 1;
break;
default:
echo "whatever!<br>";//is this nescessary?
}
}
else
{
if($count == 1){
switch($alter){
case "1":
echo "d";
$count = 2;
break;
case "2":
echo "e";
$count = 2;
break;
case "3":
echo "f";
$count = 2;
break;
default:
echo "whatever<br>"; //is this nescessary?
}
}
}
}
But honestly, excepts if its an example and that your post values are not iterative, you can do it very easily with an array, something like that :
$answers = array("a","b","c");
$answer = "WhatEver";
if($alter < 4) $answer = $answers[$alter-1];
or
$answers = array("1" => "a","2" => "b","3" => "c");
$answer = "WhatEver";
if($answers[$alter]) $answer = $answers[$alter];
Very long time made php, so syntax to check but the logic is there.
Related
<form method="post">
<select name="racebox">
<option>select</option>
<option>human</option>
</select>
<input type="textbox" name="ability" value= "">
<input type="textbox" name="strength" value= "">
<input type="submit" name="submit" value="submit">
</form>
<?php
$ability=$_POST['ability'];
$strength=$_POST['strength'];
$racepick=$_POST['racebox'];
function race($racepick){
if ($racepick === "human"):
$strength +1;
endif;
}
function modifier($num){
$modifier= floor($num/2-5);
if ($modifier >= 0):
echo " ", "+","$modifier <br>";
elseif ($modifier < 0):
echo " ", $modifier, "<br>";
endif;
}
modifier($ability);
modifier($strength);
?>
Trying to make a dnd character sheet, I want to be able to pick human and have it add a set amount to the variables gotten from 'strength' these will be predetermined prior and be different to every selection box option.
Upon review, what you should do is pass $strength to your race() function and return it with the amount of strength added to it.
$ability = $_POST['ability'];
$strength = $_POST['strength'];
$racepick = $_POST['racebox'];
$strength = race($racepick, $strength) {
switch ($racepick) {
case 'human':
$strength = $strenght + 1;
break;
case 'otherrace':
$strength = $strength + 5;
break;
}
return $strength;
}
Additional information
Functions are generally used so that programmers can re use certain parts of code. It is only usefull to use functions if you are not planning on using this code again in some other script I would like to suggest dropping the function all together and just doing the following:
$ability = $_POST['ability'];
$strength = $_POST['strength'];
$racepick = $_POST['racebox'];
switch ($racepick) {
case 'human':
$strength = $strenght + 1;
break;
case 'otherrace':
$strength = $strength + 5;
break;
}
I'm trying to use the switch statements but it's not working. My problem is for example i input LazyBoy in the textbox, that should echo LazyBoy else echo another string.
<?php
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
}
?>
Here is the form -
<form action="checkout.php" method="post" >
<input type="hidden" name ="classmap" value="<?php include('db.php');
$origin = $_POST['origin'];
$class = $_POST['class'];
$daten = $_POST['daten'];
$result = mysql_query("SELECT * FROM route WHERE route LIKE '%$origin%' AND type LIKE '%$class%' AND date LIKE '%$daten%' ");
while($row = mysql_fetch_array($result))
{
echo $row['type'];
} ?>">
</form>
You just need to check if the post variable is set and/or add a default case :
if(isset($_POST['classmap'])) {
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "Your Lazy!";
break;
case "GrayHounds":
echo "Your Gray!";
break;
default:
echo "Something";
break;
}
}
else {
echo "Something";
}
Make sure you post to the right script.
Try to put default statement to debug.
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
default:
echo "does not match with previous cases";
}
First you have to post values to define the classmap index.
<form method="post">
<input type="text" name="classmap" value="LazyBoy"/>
<input type="submit" value="submit"/>
</form>
<?php
$classmap = (isset($_POST['classmap']) ? $_POST['classmap'] : null);
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
}
?>
Your Code is correct.
I guess there is a Problem with the $_POST.
Try to verify it.
$classmap = "LazyBoy";
I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>
How to declare variables in the array using for loop. I have 3 input fields on my page, so when the submit buttons is pressed, it should process the following line of code. On my html page, there are fields named: question1, question2, and question3.
Here's the code of process.php file. It doesn't work for some reason, I suppose there are several mistakes here but I cannot find em.
<?php
$question = array();
for($j=1; $j<4; $j++) {
$question[j] = $_POST['question[j]'];
$result;
$n=1;
if($question[j] != "") {
$result = $n.'): '.$question[j].'<br/><br/>';
$n++;
}
}
echo $result;
?>
<?php
$question = array();
$result = "";
for($j=1; $j<4; j++) {
$question[$j] = $_POST["question$j"];
if($question[$j] != "") {
$result .= $j.'): '.htmlentities($question[$j]).'<br/><br/>';
}
}
echo $result;
?>
Though you don't need an array.
<?php
$result = "";
for($j=1; $j<4; j++) {
$result .= $_POST["question$j"]!="" ? htmlentities($_POST["question$j"]).'<br/><br/>':'';
}
echo $result;
?>
For starters, arrays are zero-indexed, so I think you want this:
for($j=0; $j<3; j++)
Aside form that, this doesn't evaluate the value of j:
$_POST['question[j]']
I think you might want something like this:
$_POST["question$j"]
However, if you made the indexing change above, since your elements are named starting with 1 instead of 0 then you'd need to account for that:
$_POST['question' . $j+1]
You can use following HTML code
<input type="text" name="question[a]" />
<input type="text" name="question[b]" />
<input type="text" name="question[c]" />
with following PHP code:
foreach($_POST["question"] as $key => $value)
{
// $key == "a", "b" or "c"
// $value == field values
}
Remember to sanitize Your input!
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";
}