How can i check if user changed post value? - php

I have a form for users to give reputations to people.
I'm trying to check if user changed select value to cheat by giving more points
Here is my system:
There is a select box where users can choose how many reputation to give to the user, I'm using the following code to check if user changed the values by inspecting the element:
// Validate post
if(trim($_POST["reputationToGive"]) === 1){
$added = 1;
} elseif(trim($_POST["reputationToGive"]) === 2){
$added = 2;
} elseif(trim($_POST["reputationToGive"]) === 3){
$added = 3;
} else {
// fallback event
}
Code I'm using for select box:
<option value='1'>Give 1 reputation</option>
But somehow, it always triggers the fallback event.
Looking for corrections, have a great day!

I guess the === gives you the problem.
I don't know how you wrote the selectbox. But my geuss is that you get strings back and compare it to integers. Also trim will convert it to string.
I also suggest using a switch for this.
$value = (int) trim($_POST["reputationToGive"]);
$added = 0;
switch ( $value ) {
case 1:
case 2:
case 3:
$added = $value;
break;
default:
// fallback event
break;
}
If you want to be sure the answer is not changed in the post. You could use totally different values in the form that you will translate to the right value in the script.
$value = trim($_POST["reputationToGive"]);
$added = 0;
switch ( $value ) {
case 'AD3ZY':
$added = 1;
break;
case 'B&7X1':
$added = 2;
break;
case 'Px!29':
$added = 3;
break;
default:
// fallback event
break;
}

Related

switch loop doesnt recognize zero "0" php

I have this simple function to convert the number of comments of an user to types of members.
function checkMemberN($numMessages){
$n= $numMessages;
switch ($n) {
case ($n<50): $type="New"; break;
case ($n>=50 && $n<250):$type="Frequent";break;
case ($n>=250 && $n<1000): $type="Master";break;
default: $type="undefinded";
}
return $type;
}
echo checkMemberN(0);
It looks like it doesn't recognize zero (0), because when I put 1 or a higher number it retrieves the correct user type. What am I doing wrong?
When you use switch, the first case which returns a value equal to the given one is selected. In this case, your argument (zero) is a false-y value. That's why the first case that returns false is chosen: "Frequent".
To fix it, you can do this:
if ($n<50) {
$type = "New";
} else if ($n>=50 && $n<250) {
$type = "Frequent";
} else if ($n>=250 && $n<1000) {
$type = "Master";
} else {
$type = "undefined";
}
If you still want to use switch, you can change the argument to true:
switch (true) {
case ($n<50): $type="New"; break;
case ($n>=50 && $n<250):$type="Frequent";break;
case ($n>=250 && $n<1000): $type="Master";break;
default: $type="undefinded";
}
Here, the first case which returns true will be used.

How to get answer from first try of quiz and second try of same quiz as first try in database

So, I have created a quiz with the answer options a, b, c and I want to get an answer from that option and save it to the database. How to save in the database so that the answer from the first try of the quiz is different from the second trial answer from the quiz, so that I can get the answer and call in the answer to be calculate in score function of the quiz?
what i have tried :
in my controller
public function score($id){
$user_login = Auth::user()->id;
$answers = Answer::select('user_answer')->where('jenis_quiz_id','=',$id)->where('user_id','=',$user_login)->get();//get the answer
unset($a);
unset($b);
unset($c);
$a = 0;
$b = 0;
$c = 0;
if($answers->count()) {
foreach ($answers as $answer) {
switch ($answer->user_answer) {
case 1:
$a++;
break;
case 2:
$b++;
break;
case 3:
$c++;
break;
}
}
return $a+$b+$c;
}
public function getShowResultOfQuiz($id){
$categoryquiz= JenisQuiz::findOrFail($id);
$user= Auth::user()->id;
// $instansi = Auth::user()->instansi;
// $kelas = Auth::user()->kelas;
$score= $this->score($id);
$kelas = Auth::user()->kelas;
$instansi = Auth::user()->instansi;
History::create([
'user_id'=>$user,
'jenis_quiz_id'=>$id,
'score'=> $score,
'kelas' => $kelas,
'instansi' => $instansi
]);
// $time_taken = date("H:i:s", strtotime(Answer::whereJenisQuizId($id)->orderBy('id', 'desc')->first()->time_taken));
switch ($id) {
case '1':
return view('user.pages.quizresult',compact('score','categoryquiz'));
break;
case '2':
return view('user.pages.quizanxietyresult',compact('score','categoryquiz'));
break;
case '3':
return view('user.pages.quizdepresiresult',compact('score','categoryquiz'));
break;
}
}
}
problem : can't distinguish answers from the first try of quiz trial and second try of quiz
(from same quiz form but i taken it twice, and how to make the difference between it.
My code result above is score from first try added to the second try,how to not added it??????

Switch & Case multiple selections

I got an issue with switch.
Right now from my understanding it works like this:
if ( sizeof( $a ) !== sizeof( $types ) ) {
$type = $a[ 0 ];
switch ( $type ) {
case 'Red' :
$type = 'winered';
break;
case 'blue' :
$type = 'royalblue';
break;
case 'yellow' :
case 'lime' :
break;
case 'beige' :
$type = 'bright';
break;
default :
$type = get_option( 'my_option' );
break;
}
} else {
$type = get_option( 'my_option' );
}
So far so good. Whatever I select, it shows the case.
My issue is, it does it only one by one, I am able to select multiple cases like
case Red: case Blue:
$type = 'winered';
break;
But this won't work for me. In my scenario it is a checkbox I got case "Red" AND case "Blue" selected and want to display both "results": "winered" AND "royalblue". Right now it falls back to royalblue.
Any suggestions?
Thank you!
I dont think it is possible with a switch case to select multiple outcomes. I'd rather use an if statement something like:
if($type = 'red' || $type = 'blue'){
$type = 'winered';
$type = $type.'royalblue';
}
It doesn't really make sense why it would fall back to 'royalblue' other than:
'Red' != 'red', so it never really goes into the first case
Maybe this is how you have the types stored in $a, so that $a[0] is in fact 'blue', I would check that.
In any case, if you were interested in combination of different conditions, I would think that 'regular' if-then-else is the way to go. Case is generally faster, but offers itself for 'simpler' conditionals.
I hope this helps!
Your code is incomplete. However, I think the key is here:
$type = $a[ 0 ];
switch ( $type ) {
You only check the first value of $a. You can check all its values using a simple foreach:
// Put the selected values here; will join them at the end to get a string
$selected = array();
if (count($a) != count($types)) {
foreach ($a as $type) {
switch ($type) {
case 'Red':
$selected[] = 'winered';
break;
case 'blue':
$selected[] = 'royalblue';
break;
case 'yellow':
case 'lime':
// nothing here?!
break;
case 'beige':
$selected[] = 'bright';
break;
default:
$selected[] = get_option('my_option');
break;
}
}
} else {
$selected[] = get_option('my_option');
}
// Join the selected type with spaces
$type = implode(' ', $selected);

How to set a variable value based on conditions set by other variables

So I am new to PHP, and am currently just doing a little project as practice, I've managed to get down a few lines of code without falling over... but am a bit stuck here.
Essentially, what my script currently does is check three different variables that I have set (each a true/false option) and distinguishes if there is only one true option selected (out of the 3 options, only one can be true, the other 2 must be false). If only 1 value is set to true, the rest of the code runs; if multiple values are set to true, or no values are set to true, it shows an error prompt for the user.
Once this check is done, I wanted to then set the value of $name for example, based on records linked to the relevant variable that is true... This is what I have come up with, but it doesn't seem to work...
if ($value1 == "true") {$name = $result1;}
else if ($value2 == "true") {$name = $result2;}
else if ($value3 == "true") {$name = $result3;}
else exit (0)
So i essentially want to set the $name variable by identifying which of the 3 value variables is true, and then setting $name with the relevant variable retrieved in the $result
Any help would be appreciated. And before anyone goes off on one... I know I may sound a bit mad... but we all have to start somewhere!!
Thanks
It would look much nicer with a switch:
switch(true){
case $value1:
$name = $result1;
break;
case $value2:
$name = $result2;
break;
case $value3:
$name = $result3;
break;
default:
exit();
}
In case you need to make sure only one of the statements is true, validate that prior using this:
//In case you need to make there is only a single true statement
$found = false;
for($i=1; $i<4; $i++) {
$value = "value".$i;
if($$value) {
if($found) {
exit("More than one 'true' statement");
}
$found = true;
}
}
Dracony's answer looks nice indeed, but will fail when multiple values are set to true. For more flexibility, you should consider mapping the values into arrays, and tracking the state (amount of values that are true) with a flag variable. Find a fully commented example that will satisfy all conditions below. Additionally, this code will work with arrays of any length (you can add conditions by simply putting more values in $values and $results).
// store the data in arrays for easier manipulation
$values = array($value1, $value2, $value3);
$results = array($result1, $result2, $result3);
// set a flag to check the state of the condition inside the loop
// it keeps track of the index for which the value is true
$flag = -1;
$name = NULL;
// use for and not foreach so we can easily track index
for ($i = 0; $i < count($values); $i++) {
// if no index has been found 'true' yet, assign the current result.
if ($values[$i] === true) {
if ($flag === -1) {
$flag = $i;
$name = $results[$i];
}
// if a 'true' value has been found for another index
// reset the name var & stop the loop
if ($flag > -1 && $flag !== $i) {
$name = NULL;
break;
}
}
}
if ($name) {
// run code when only 1 value is true
} else {
exit();
}

How can I get this PHP variable to be determined by the value of another user selected radio button

$door = $_POST["doorType"];
$doorWidth;
if ($door=="Single")
{
$doorWidth = $width;
}
else if ($door=="Double")
{
$doorWidth = $dOneWidth;
}
When I run the page it doesn't recognize the variable $doorWidth?
$doorWidth;
doesn't assign anything. It only returns the variable ... to anything. Doing this PHP is accessing the variable, causing a notice. Write for example:
$doorWidth = NULL; // assigns something (some default value if $door isn't "Signle" nor "Double")
I guess that $door has a value far from Single|Double. This may be caused by another error in your application. You should learn, that you should in any case set a proper default value for a variable if you are about to assign to it from into a conditional statement (like if):
$doorWidth = 'not set!';
if ($door=="Single")
{
$doorWidth = $width;
}
else if ($door=="Double")
{
$doorWidth = $dOneWidth;
}
Further note about the switch statement which has a default: branch:
switch($door) {
case 'Single' :
// do something
break;
case 'Double' :
// do something else
break;
default:
die('$door has a value far from 'Single|Double'. Currently: ' . $door);
}

Categories