Forum Moderators: coopster

Message Too Old, No Replies

Simple If/Then/Else php question

php if then else statements

         

launch3

5:52 pm on May 11, 2009 (gmt 0)

10+ Year Member



Hello.

I am attempting to setup a very simple php script.

Here's the goal.

I'm asking my visitors to solve a puzzle. It'll be words they have to put in the right order to make a complete sentence or phrase.

Here's where the php comes into play:

If they type in the correct sentence/phrase into the form field, they are redirected to PAGE A (Success page).

If they get the sentence/phrase incorrect, they are redirected to PAGE B (Oops, try again).

Any advice on how to create this would be appreciated. I am very do-it-yourself oriented and looking for good tutorials.

Thanks,
Jeff

mooger35

6:36 pm on May 11, 2009 (gmt 0)

10+ Year Member



Instead of using if and elseif maybe switch [php.net] would work better for you?

rob7591

9:49 pm on May 11, 2009 (gmt 0)

10+ Year Member



create a page called process.php with this code:

<?
$answer = 'hello'; //replace hello with what ever the answer is
$a = "http://example.com/correct.html"; //replace that with the correct response page
$b = "http://example.com/incorrect.html"; //replace with incorrect response page
if ($_GET['response'] == $answer) {
header("Location: $a");
} else {
header("Location: $b");
}
?>

have your form where they input their response look something like this:

<form action="process.php" method="get">
<input type="text" name="response" />
</form>

Then have your correct response page and incorrect response page.. There's a fairly detailed outline for you.

launch3

10:12 pm on May 11, 2009 (gmt 0)

10+ Year Member



Thank you Rob.
I've got it working.
It's going to be a heavily used simple script.
Been absorbing php quickly. It's much easier to understand than I anticipated.

mooger35, I hadn't heard of a switch statement. How clever. I may have use for that in another part of my project.

naiquevin

5:53 am on May 12, 2009 (gmt 0)

10+ Year Member



i do such things this way..

Instead of 3 files, you can have just one php file.. and the form calls itself, method=post. Following structure can be used for coding then

<?php


if(isset($_POST['submit'])) { //1 if form is submitted

$show_form = false; // this is a flag

if($_POST['answer'] == '$answer') {
echo 'correct';
}

else {
echo 'wrong ans';
$show_form = true; // flag is reset to true
}

} //1 ends

$show_form = true; //so that form is displayed on first visit

if($show_form == true) {

echo '<form method="post" action="thisfile.php">'; // calls itself
echo '<input type="text" name="answer"/>';
echo '</form>';
}

?>

This way if the ans is correct itonly shows the msg.
if it is incorrect it shows 'wrong' msg and shows the form ..
When the page opens for the first time it shows the form..

If... else for form validation may also be included and if validation fails reset flag to true..