PHP Forms checkbox calculation - php

I am trying to perform some calculations with a form but every time i try to work with checkboxes it goes wrong.
The checkboxes are beign set on value 1 in the form itselff and are being checked if there checked or not.
$verdieping = isset($_POST["verdieping"]) ? $_POST["verdieping"] : 0;
$telefoon = isset($_POST["telefoon"]) ? $_POST["telefoon"] : 0;
$netwerk = isset($_POST["netwerk"]) ? $_POST["netwerk"] : 0;
When i try to do calculations every works expect for the options with the checkboxes.
When both checkboxes (telefoon & netwerk) are selected the value should be 30.
If only one is selected the value should be 20.
But no mather what i have tried to write down it always give problem, and it always uses 20, never the value 30.
How do i solve this problem? Or suppose i am writing the syntax all wrong to lay conditions to a calculation? Any input appreciated.
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
$verdieping = $_SESSION["verdieping"];
$telefoon = $_SESSION["telefoon"];
$netwerk = $_SESSION["netwerk"];
if ($oppervlakte <= 10)
$tarief = 100;
if ($oppervlakte > 10 && $oppervlakte <= 20)
$tarief = 90;
if ($oppervlakte > 20)
$tarief = 80;
if($verdieping == 1)
{
$prijsVerdieping = $oppervlakte * 120;
}
else
{
$prijsVerdieping = 0;
}
if(($telefoon == 1) && ($netwerk == 1))
{
$prijsCom = 30; // never get this value, it always uses 20
}
if(($telefoon == 1) || ($netwerk == 1))
{
$prijsCom = 20;
}
$prijsOpp = $tarief * $oppervlakte; // works
$totalePrijs = $prijsOpp + $prijsVerdieping + $prijsCom; //prijsCom value is always wrong
Regards.
EDIT: full code below in 2 php files
<?php
if (!empty($_POST))
{
$standnaam = $_POST["standnaam"];
$oppervlakte = $_POST["oppervlakte"];
//value in the form van checkboxes op 1 zetten!
$verdieping = isset($_POST["verdieping"]) ? $_POST["verdieping"] : 0; //if checkbox checked value 1 anders 0
$telefoon = isset($_POST["telefoon"]) ? $_POST["telefoon"] : 0;
$netwerk = isset($_POST["netwerk"]) ? $_POST["netwerk"] : 0;
if (is_numeric($oppervlakte))
{
$_SESSION["standnaam"]=$standnaam;
$_SESSION["oppervlakte"]=$oppervlakte;
$_SESSION["verdieping"]=$verdieping;
$_SESSION["telefoon"]=$telefoon;
$_SESSION["netwerk"]=$netwerk;
header("Location:ExpoOverzicht.php"); //verzenden naar ExpoOverzicht.php
}
else
{
echo "<h1>Foute gegevens, Opnieuw invullen a.u.b</h1>";
}
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="form1">
<h1>Vul de gegevens in</h1>
<table>
<tr>
<td>Standnaam:</td>
<td><input type="text" name="standnaam" size="18"/></td>
</tr>
<tr>
<td>Oppervlakte (in m^2):</td>
<td><input type="text" name="oppervlakte" size="6"/></td>
</tr>
<tr>
<td>Verdieping:</td>
<td><input type="checkbox" name="verdieping" value="1"/></td>
<!--value op 1 zetten voor checkbox! indien checked is value 1 -->
</tr>
<tr>
<td>Telefoon:</td>
<td><input type="checkbox" name="telefoon" value="1"/></td>
</tr>
<tr>
<td>Netwerk:</td>
<td><input type="checkbox" name="netwerk" value="1"/></td>
</tr>
<tr>
<td><input type="submit" name="verzenden" value="Verzenden"/></td>
</tr>
</table>
2nd page with calculations:
<?php
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
$verdieping = $_SESSION["verdieping"];
$telefoon = $_SESSION["telefoon"];
$netwerk = $_SESSION["netwerk"];
if ($oppervlakte <= 10)
$tarief = 100;
if ($oppervlakte > 10 && $oppervlakte <= 20)
$tarief = 90;
if ($oppervlakte > 20)
$tarief = 80;
if($verdieping == 1)
{
$prijsVerdieping = $oppervlakte * 120;
}
else
{
$prijsVerdieping = 0;
}
if(($telefoon == 1) && ($netwerk == 1))
{
$prijsCom = 30;
}
if(($telefoon == 1) || ($netwerk == 1))
{
$prijsCom = 20;
}
$prijsOpp = $tarief * $oppervlakte; // werkt
$totalePrijs = $prijsOpp + $prijsVerdieping + $prijsCom;
echo "<table class=\"tableExpo\">";
echo "<th>Standnaam</th>";
echo "<th>Oppervlakte</th>";
echo "<th>Verdieping</th>";
echo "<th>Telefoon</th>";
echo "<th>Netwerk</th>";
echo "<th>Totale prijs</th>";
echo "<tr>";
echo "<td>$standnaam</td>";
echo "<td>$oppervlakte</td>";
echo "<td>$verdieping</td>";
echo "<td>$telefoon</td>";
echo "<td>$netwerk</td>";
echo "<td>$totalePrijs</td>";
echo "</tr>";
echo "</table>";
?>
Terug naar het formulier
</body>
</html>

One problem I've noticed are these lines,
if(($telefoon == 1) && ($netwerk == 1)) {
$prijsCom = 30; // will get set to 30.
}
if(($telefoon == 1) || ($netwerk == 1)) {
$prijsCom = 20; // will now be set to value of 20.
}
Here is why, if $telefoon and $netwerk are both 1, $prijsCom is set to the value of 30. It leaves that if block and goes down onto the next one, i.e.
if(($telefoon == 1) || ($netwerk == 1)) {
$prijsCom = 20;
}
It will evaluate to true since $telefoon == 1 evaluates to true and will override the value of $prijsCom to be 20.
Depending on how the code will be used, as a possible work-around, you could add the || condition first, so the value is set to 20 whether $telefoon or $netwerk is set to 1 and then check to see if they both are 1.
Update:
When looking at your code, I notice you are using $_SESSION variables, but you have not called session_start() at the beginning of the file,
<?php
session_start(); // <--you need to call this first
$standnaam = $_SESSION["standnaam"];
$oppervlakte = $_SESSION["oppervlakte"];
...
This may or may not be where your other problem lies, but whenever you use $_SESSION you need to call session_start first.

Call session_start(); after <?php.

Related

Color depending on value

I use this code multiple times in my script. Is there a way to shorten this code? Thank you in advance.
if ($aUurverschil < 0){$avroegerkleur = "red";}
if ($aUurverschil > 0){$avroegerkleur = "green";}
if ($aUurverschil == 0){$avroegerkleur = "#48f442";}
if ($bUurverschil < 0){$bvroegerkleur = "red";}
if ($bUurverschil > 0){$bvroegerkleur = "green";}
if ($bUurverschil == 0){$bvroegerkleur = "#48f442";}
etc etc.
I use them in a div:
<div style="display:inline;color:<? echo $avroegerkleur;?>;">
You can abstract this logic:
if ($bUurverschil < 0){$bvroegerkleur = "red";}
if ($bUurverschil > 0){$bvroegerkleur = "green";}
if ($bUurverschil == 0){$bvroegerkleur = "#48f442";}
into a function, for example:
function getColor($uurverschil) {
return ($uurverschil < 0 ? "red" :
($uurverschil > 0 ? "green" :
("#48f442")));
}
Then anywhere you want to use that logic, just invoke that function with the value you're examining:
<div style="display:inline;color:<? echo getColor($aUurverschil); ?>;">

PHP basic: why my variable showing wrong value?

I am new to PHP. I am trying to create a simple form where user will submit there name and mark they got in the exam.
<form action="" method="post">
<input type="text" name="name" id="" placeholder="Your name">
<input type="number" name="mark" id="" placeholder="Your Mark">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST["submit"])){
$name = $_POST['name'] ;
$mark = $_POST['mark'];
if( $mark > 80 ){
$result = "A+";
}elseif($mark > 70 && $mark < 80){
$result = "A";
}
elseif($mark > 60 && $mark < 70){
$result = "A-";
}
elseif($mark > 40 && $mark < 60){
$result = "B";
}else{
$result = "Fail";
}
echo $result;
}
?>
But if I echo the result variable it is always showing 'Fail'. What is I am doing wrong? thanks
As mentioned in the comments, when comparing ranges, you need to consider the corner cases:
$mark >= 70 && $mark < 80
Also there are few ways to simplify your code: If you check for marsk >= 80 in the first IF, there is no need to check for that in the next elseif:
if( $mark >= 80 )
{
$result = "A+";
}
elseif($mark >= 70)
{
$result = "A";
}
elseif($mark >= 60)
{
$result = "A-";
}
elseif($mark >= 40)
{
$result = "B";
}
else
{
$result = "Fail";
}
echo $result;

How to check prime number with an input set as LIMIT

So i have the code to check for Prime numbers with value that is inputted. My question is, how can i turn my code so that the table can be dynamic in sets of 10 and the max is 100? So that the input can only take increments of 10 and the max value you can enter 100?
My current code right now is set to 10 columns and 4 rows so is there a way to make this change (dynamic i guess?) to change with the input increments of 10?
Here is my code:
<form method="post" action="">
<table border="2" width="1180px">
<thead>
<center>
Number Chart</center>
</thead>
<?php
error_reporting(0);
function isPrime($n)
{
if ($n == 1) return false;
if ($n == 2) return true;
if ($n % 2 == 0)
{
return false;
}
$i = 2;
for ($i = 2; $i < $n; $i++)
{
if ($n % $i == 0)
{
return false;
}
}
return true;
}
if (isset($_POST['value']) && $_POST['value'] != 0)
{
/* #var $start type */
$start = $_POST['value'];
}
else
{
$start = 1;
}
$n_cols = 10;
$n_rows = 5;
for ($i = 0; $i < $n_rows; $i++) //
{
$col = '';
for ($j = 0; $j < $n_cols; $j++)
{
$number = ($start - $i - ($j * $n_cols));
if (isPrime($number) == true)
{
//if prime color it red
$col.= '<th style="color:red">' . ($start - $j - ($i * $n_cols)) .
'</th>';
}
else
{
$col.= '<th>' . ($start - $j - ($i * $n_cols)) . '</th>';
}
}
$out.= '<tr>' . $col . $row . '</tr>';
}
echo $out;
?>
<tr>
<thead colspan=10>
<center>
<label for="input">Enter Limit:</label>
<input type="text" name="value" style="width: 60px">
<input type="submit" name="submit" value="Submit">
</center>
</thead>
</tr>
</table>
</form>
if (($_POST['value'] % 10) != 0 || $_POST['value'] >100 ){
echo 'you must enter a valid value';
}else{
//all the code you want to run only if the number posted is valid
}
the % is Modulo, see http://php.net/manual/en/language.operators.arithmetic.php for more details

Can I have more than one while(!feof) loop in a program?

If I'm trying to display a table (which I've accomplished with a while loop) but also display a count underneath it. Do I add another while loop? Or a seperate for loop? How would I do that? I need to count the number of performances (Ive got that working) but it wont tally the number of performances in Asheville. How do I target that variable by itself?
> <?php print ("<h1>Upcoming Performances in 2015</h1>"); print
> ("<table border =\"1\">"); print("<tr><th align =
> \"left\">Date</th><th align = \"left\">Venue</th><th align =
> \"left\">City</th><th align = \"right\">Ticket Price</th></tr>");
>
> $count = 0; $ashevilleCount = 0; $eventFile =
> fopen("performances.txt", "r"); $schedule = fgets($eventFile);
>
>
> while(!feof($eventFile)) { list($date, $venue, $city, $ticketPrice) = explode(":", $schedule);
> print("<tr><td>$date</td>"); print("<td>$venue</td>"); print("<td>$city</td>"); print("<td>$ticketPrice</td>");
> $schedule = fgets($eventFile);
> }
>
> for($count = 1; $count <= 5; $count = $count + 1) { $total = fgets($eventFile); $count = $count + $total;
> }
> if ($city == Asheville)
> $ashevilleCount = $ashevilleCount + $count;
>
>
>
>
>
> fclose($eventFile);
> print ("</table>");
>
> print ( "<p class=\"alert\">Lower cost venues are marked with
> *</p>"); print ("<p>NUMBER OF PERFORMANCES: $count</p>"); print ("<p>NUMBER OF PERFORMANCES IN ASHEVILLE: $ashevilleCount</p>");
>
>
>
>
> ?>
You need to take a look at your if statements.
if($condition === true){
//executes if $condition is true
} elseif($condition === 1) {
//executes if $condition is 1
} elseif($condition === 2 || $condition === 3){
//executes if $condition is 2 OR condition is 3
} elseif($condition === 4 && $otherCondition !== "foo"){
//executes if $condition is 4 AND $otherCondition is NOT "foo"
} else {
//executes if no other statements are true
}
This piece of code:
elseif
($charType == human or dwarf and $goldSpent <= 10)
$supplyTokens = $_POST['supplyTokens'] + 10;
Needs to look like:
} elseif( ( $charType=="human" || $charType=="dwarf" ) && $goldSpent <= 10) {
$supplyTokens = $_POST['supplyTokens'] + 10;
}
Remember:
|| = "or"
&& = "and"
test != "test" - make sure your strings are enclosed in quotation marks
See:
http://php.net/manual/en/control-structures.if.php
http://php.net/manual/en/control-structures.elseif.php
http://php.net/manual/en/language.operators.comparison.php
Here's your code cleaned up. What was done:
Changed all the print() commands to concatenated echos.
Fixed the conditionals
You don't need to check for $goldSpent <= 10 in your elseifs as you have already checked that by not being in $goldSpent > 10
I personally prefer || and && as opposed to or and and
Added curly brackets {}
Thing to consider:
What would happen if any of those $_POST values are empty??
<?php
$charName = $_POST['charName'];
$charType = $_POST['charType'];
$healthTokens = $_POST['healthTokens'];
$expTokens = $_POST['expTokens'];
$supplyTokens = $_POST['supplyTokens'];
$goldSpent = $healthTokens / 10 + $expTokens / 2 + $supplyTokens / 25;
if ($goldSpent > 10) {
echo "<h1>HEY THERE, $charName!</h1>" .
"<p>YOU SPENT MORE GOLD THAN YOU HAVE!</p>" .
"<p>GO BACK AND TRY THAT AGAIN - YOU HAVE 10 GOLD PIECES..</p>";
} elseif ($charType == 'elf') {
$healthTokens = $_POST['healthTokens'] + 5;
} elseif ($charType == 'wizard') {
$expTokens = $_POST['expTokens'] + 2;
} elseif ($charType == 'human' || $charType == 'dwarf') {
$supplyTokens = $_POST['supplyTokens'] + 10;
}
$totalGold = 10;
$goldLeft = $totalGold - $goldSpent;
echo "<h1>You have created $charName the $charType!</h1>" .
"<p>$charName has <strong>$healthTokens</strong> health tokens," .
"<strong>$expTokens</strong> experience tokens, and" .
"<strong>$supplyTokens</strong> supply tokens.</p>" .
"<p>You received some bonus tokens! :)</p>" .
"<p>$charName has spent <strong>$goldSpent</strong> gold pieces, " .
"and has <strong>$goldLeft</strong> gold pieces left.</p>";

php - undefined variable - declared inside if statement

I have the following code that suppose to change the background color after I enter the RGB color codes and click submit.
I don't know for what reason I get the "Undefined variable" and have a black background color before I click the submit button
< ?php
error_reporting(E_ALL);
ini_set('display_errors',true);
$form = "< form method='post' action=$_SERVER[PHP_SELF] >\n
R: < input type='text' name='r' >
G: < input type='text' name='g' >
B: < input type='text' name='b' >
< input type='submit' name='buton' value='go' >\n";
< /form >
$hexa = array();
$culoareHexa = array();
function &decimal2hexa($valoare) {
$valoriHexa = array('0'=>'0', '1'=>'1', '2'=>'2', '3'=>'3', '4'=>'4', '5'=>'5', '6'=>'6', '7'=>'7', '8'=>'8', '9'=>'9', '10'=>'A', '11'=>'B', '12'=>'C', '13'=>'D', '14'=>'E', '15'=>'F' );
if ($valoare <= 15) {
$numarHexa[] = $valoare;
$numarHexa[] = 0;
} else {
while ($valoare >= 15) {
$catul = $valoare / 16;
settype($catul, 'int');
$restul = $valoare % 16;
$valoare = $catul;
$numarHexa[] = $restul;
}
$numarHexa[] = $catul;
}
krsort($numarHexa);
foreach ($numarHexa as $key => $value) {
if ($value > 9) {
$numarHexa[$key] = $valoriHexa[$value];
}
}
$numarHexa = array_values($numarHexa); //reindexez si pastrez valorile pe pozitia initiala
return $numarHexa;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
echo $form;
} else {
if (!isset($_POST['r']) || !is_numeric($_POST['r']) || ($_POST['r'] > 255) || ($_POST['r'] < 0) ||
!isset($_POST['g']) || !is_numeric($_POST['g']) || ($_POST['g'] > 255) || ($_POST['g'] < 0) ||
!isset($_POST['b']) || !is_numeric($_POST['b']) || ($_POST['b'] > 255) || ($_POST['b'] < 0)) {
echo "date invalide!";
echo $form;
} else {
$culoareHexaR =& decimal2hexa($_POST['r']);
$culoareHexaG =& decimal2hexa($_POST['g']);
$culoareHexaB =& decimal2hexa($_POST['b']);
var_dump($_POST);
var_dump($culoareHexaR);
var_dump($culoareHexaG);
var_dump($culoareHexaB);
$culoareHexa = array_merge($culoareHexaR, $culoareHexaG, $culoareHexaB);
var_dump($culoareHexa);
$culoareHexaString = "";
for ($i = 0; $i < count($culoareHexa); $i++) {
$culoareHexaString .= $culoareHexa[$i];
}
echo $culoareHexaString;
}
}
? >
< html >
< body bgcolor="< ?php echo $culoareHexaString ? >">
< /body >
< /html >
If I declare the $culoareHexaString outside the if statement, it works just fine but I do not understand why.
in the following example it is not necessary to declade the $c variable outside the if statement.
$a = 5;
$b = 6;
if ($a > $b) {
echo "this will not be print";
} else {
$c = $a+$b;
}
$c variable will have a value of: < ?php echo $c ? >
what I am missing?
thanks!
Here:
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
...
} else {
// code not executed on GET/initial page view
}
You initialize $culoareHexaString in a block that is never executed, because the first view/non-submit is a GET request, and thuse the else condition is ignored.
Try initializing a default value outside that block, like:
$coloareHexaString = '#000000'; // default value?
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
...
} else {
// code not executed on GET/initial page view
}
As for your example, echoing $c would also be undefined if $a < $b, as it was never initialized.
<?php
$a = 7;
$b = 6;
if ($a > $b) {
echo "this will not be print";
} else {
$c = $a+$b;
}
echo $c; // this will be undefined.
?>
Because $culoareHexaString is not setted.
When you use if-else statement, actually there will be code blocks and at the run time according to the statement related block content is handling.
for detecting value setting, use isset() method.
Also you can set default color at the beginning like;
< ?php
error_reporting(E_ALL);
ini_set('display_errors',true);
$culoareHexaString = "#000000";
$form = "< form method='post' action=$_SERVER[PHP_SELF] >\n
R: < input type='text' name='r' >
G: < input type='text' name='g' >
B: < input type='text' name='b' >
< input type='submit' name='buton' value='go' >\n";
< /form >
$hexa = array();
$culoareHexa = array();
.....

Categories