Switch Statements not working - php

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

Related

PHP overriding isset value, showing new output

So, I have this code
<?php
if(!isset($_POST["step1_submit"]))
{
echo "Fill step1!";
step1();
}
function step1()
{
if(isset($_POST["step1_submit"]))
{
step2();
}
else
{
echo '<form action="" method="post">STEP 1: <input name="step1_input"/><input name="step1_submit" type="submit" value=">>STEP 2>>"/></form>';
}
}
function step2()
{
echo "reached step 2";
if(isset($_POST["step2_submit"]))
{
echo '<br/>'.$_POST["step2_input"];
step3();
}
else
{
echo '<form method="post">STEP 2: <input name="step2_input"/><input name="step2_submit" type="submit" value=">>STEP 3>>"/></form>';
}
}
function step3()
{
echo '<strong>WELL DONE</strong>';
}
?>
It shows the input for step1, but never gets to show step2. In my opinion, it gets stuck on calling the function step2, because while doing it, the isset($_POST(step1_submit)) changes it value to NULL.
How can I manage to make this code work? It should be like: filling step 1 input >> getting to fill step 2 input >> submit step 2 >> get to see the 'WELL DONE' echo.
Basically the conditional statement on top needs an else branch:
if(!isset($_POST["step1_submit"]))
{
echo "Fill step1!";
step1();
} else {
step2();
}
...
However, if you have more steps it should look like this:
switch(TRUE) {
case isset('step1_submit') :
step2();
break;
case isset('step2_submit') :
step3();
break;
...
default:
echo "Fill step1!";
step1();
}
Then change your functions to:
function step1()
{
echo '<form action="" method="post">STEP 1: <input name="step1_input"/><input name="step1_submit" type="submit" value=">>STEP 2>>"/></form>';
}
function step2()
{
echo '<form action="" method="post">STEP 2: <input name="step2_input"/><input name="step2_submit" type="submit" value=">>STEP 3>>"/></form>';
}
...
The if conditionals aren't required there.

$_POST within the class

I've got a class Posts which has public function displayPosts:
public function displayPosts($numberOf = 50){
$result = $this->mysqlResult($this->id);
$i = 1;
while ($post = mysql_fetch_object($result)) {
$added = new Time;
$elapsed = $added->displayElapsedSignificant($post->data);
echo "
<h1>$post->title</h1>
<i>$elapsed</i>
<p>$post->text</p>
<h3>...komentarze...</h3>";
$this->displayComments($post->id);
"<hr />";
if($i == $numberOf) break;
else $i++;
}
}
And the private function displayComments:
private function displayComments($id){
$postComments = new Comments;
switch($this->getElement($id, "comment_type")){
case 1:
if($_POST) {
echo addSecurity($_POST['comment']);
}
else {
echo '
Zostaw komentarz:
<form action="#" method="post">
<textarea id="comment"></textarea><br />
<input type="submit" value=" Dodaj komentarz " />
</form>
';
}
break;
case 2:
//kod dla fb
break;
case 3:
//kod dla obu
break;
default:
break;
}
}
My problem is that the form doesn't work: the $_POST is always empty. Any solution?
You need name attribute for form values to be send to server - like this:
<textarea id="comment" name="comment"></textarea>
$_POST is filled with name (not id) attributes as keys and values as values :)

Different page titles with one header file?

How do you do multiple page titles with on header file? Theres one thing though. For the index page, i've got
error_reporting(0);
if ($_GET["error"]=="404") {
include("forum/styles/art_air/web_template/overall_header.php");
include("include/404");
include("include/index");
include("forum/styles/art_air/web_template/overall_footer.php");
} else {
include("forum/styles/art_air/web_template/overall_header.php");
include("include/index");
include("forum/styles/art_air/web_template/overall_footer.php");
}
So i would have the header before anything else. So how would i manage to make so that
index?error=404 and index have different titles? Thanks in advance.
In overall_header.php
<?php
$title = "Hello, wolrd!";
if ( $_GET["error"] == "404" ) {
$title = "Error";
}
?>
<title><?php echo $title; ?></title>
Use JavaScript and document.title.
Example:
<script language="javascript">document.title = "My Title"</script>
JS can be used in body.
Another method is to set a $GLOBAL variable before including everything.
Example:
error_reporting(0);
$GLOBALS['404'] = 0;
if ($_GET["error"]=="404") {
$GLOBALS['404'] = 1;
include("forum/styles/art_air/web_template/overall_header.php");
include("include/404");
include("include/index");
include("forum/styles/art_air/web_template/overall_footer.php");
} else {
$GLOBALS['404'] = 0;
include("forum/styles/art_air/web_template/overall_header.php");
include("include/index");
include("forum/styles/art_air/web_template/overall_footer.php");
}
In your overall_header.php:
if($GLOBALS['404'] == 1) echo '<title>404: Not Found</title>';
else echo '<title>My Title</title>';
You could try a switch
<?php
$page = $_SERVER['PHP_SELF'];
switch($page) {
case "index.php":
echo "<title>My Homepage</title>";
break;
case "apples.php":
echo "<title>The Best Apples!</title>";
break;
case "bananas.php":
echo "<title>We Sell Bananas</title>";
break;
}
?>

How to iterate through an array then replace data of a matching id

Okay so what i am trying to do is Iterate through Json decoded array then search for an ID(key) then post that data into a form for editing then encode it then save it it seems like such an easy task however i am not using a data base or java or java script i have to do this using only Json, PHP and HTML my main code(Controller) file is as follows
<?php
$file_name = 'engagements.json'; // Serialized speaking engagments
/**
* Controller for Speaking Engagements
*/
if (!isset($_REQUEST['act']) || !$action = $_REQUEST['act']){
$action = 'list';
} //End If
switch ($action) {
case 'list': // List
$json_data = file_get_contents($file_name);
if (!$engagements = json_decode($json_data, true)) { // Convert serialized data to array
$engagements = array();
} //End If
include 'engagements_list.phtml';
break;
case 'view': // View
$json_data = file_get_contents($file_name);
$temp_array = json_decode($json_data);
foreach($temp_array as $key=>$id){
if($id->ID == 2){
echo "got it \n";
echo "ID: $id->ID \n";
echo "Title: $id->Title \n";
echo "Description: $id->Description \n";
}// End If
}
break;
case 'add': // Add
$temp_array = array();
$file = file_get_contents($file_name);
$json_data = json_decode($file);
$high_value = count($json_data);
$high_value++;
$temp_array['ID'] = $high_value;
$temp_array['Title'] = $_POST['Title'];
$temp_array['Description'] = $_POST['Description'];
$json_data[] = $temp_array;
file_put_contents($file_name, json_encode($json_data));
include 'engagements_add.phtml';
break;
case 'edit': // Edit
$file = file_get_contents($file_name);
$json_data = json_decode($file, true);
// what comes next here
include 'engagements_edit.phtml';
break;
case 'delete': // Delete
break;
default:
throw(new Exception('Invalid action given'));
break;
}//End Switch
exit;
<!-- Edit View -->
<form action="engagements.php?act=edit?ID=<?php $_GET['ID']?>" method="get">
<table>
<tr><td><input type="hidden" name="ID"></td></tr>
<tr><td><input type="text" style="width:500px;" name="Title"></td></tr>
<tr><td><textarea cols="40" rows="2" style="width: 500px; height:250px;" name="Description"></textarea></td></tr>
<tr><td><input type="submit" name="Submit" value="Submit"/></td></tr>
</table>
</form>
please help me i have searched everywhere for an answer but can find any resources that explain how to do this properly
Tiny one point.
<form action="engagements.php?act=edit?ID=<?php $_GET['ID']?>" method="get">
I'm assuming you meant to type like this:
<form action="engagements.php?act=edit&ID=<?php echo $_GET['ID']?>" method="get">
The $_GET statement was missing an echo, too.
UPDATE:
I notice php close tag ?> missing until EDIT VIEW. And 'view' part in switch, why you echo ID property? It might be following:
echo "ID: $id['ID'] \n";

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