php assistance with quiz results - php

I have a module that the user clicks through and watches a video. There are progress checks throughout that are not graded but the requester now wants the user to have to retake the progress check if they didn't get all of the answers correct. I believe the line of code for this needs to be in the next button back to progress check. Thank you for any help!
Here is my code:
progress results.php
if ($feedback = "Correct!") {
echo '<a id="next" href="' . $filename . '.php?page=' . ($page) . '">Next</a>';
}
else {
echo '<a id="next" href="progress_check.php?page=' . ($page+1) . '">Next</a>';
}

In PHP, we have three kinds of "=" uses :
Assignment operator : =
$var = 'Alex';
Here, we just asign the value of Alex to a variable called $var, we do not make any other type of operation as comparing values.
Comparison operator : Equal to ==
$var == 'Alex';
Here, we check if the variable $var has a value equal to Alex. Frequently used in an if statement to compare two variables.
if ($var == 'Alex') {
# code...
}
Comparison operator : Identical to ===
And here, we make sure if the variables have the same values and an identical type, for example comparing a string and an integer, like this.
$var = '5';
if ($var === 5) {
# code...
}
As you see, we are using an if statement to check if either has the same type, not just the same value, in this case, the result is false.
Your case
Try this :
if ($feedback == "Correct!") {
echo '<a id="next" href="' . $filename . '.php?page=' . ($page) . '">Next</a>';
} else {
echo '<a id="next" href="progress_check.php?page=' . ($page+1) . '">Next</a>';
}
More information about this topic right here : Comparison Operators
I hope that help you to understand the behavior.

Related

How to display previously assigned variable from past session

I'm a new coder and I'm trying to write some code for a simple math game where you have to give the value of the second int in order to get to the sum.
I have it so the user submits their answer through a form and I want to have it so it checks the answer and if it is wrong it will display the correct answer. The issue I'm having is that after the user answers the question a new one is loaded and the code is checking the answer for the new question instead of the old one, displaying the answer to the new question.
For example, if the sum of int 1 and int 2 is 30 and the value of int 1 is 20, the value of int 2 must be 10 which is what the user would submit into the form.
I want to have it display "correct" or, if the user got it wrong, then "the correct answer is 10" but this is not the case because after the user answers the question it checks the answer for the new generated question and ends up displaying "the correct answer is 20" or whatever the new value of int 2 is. I do not know how to have it evaluate the answer for the old question as the variables are overwritten with the new question.
<?php
echo "<h2 id='heading'>php program to add two numbers...</h2><br />";
$val1 = rand(1, 100);
$val2 = rand(1, 100);
$sum = $val1 + $val2; /* Assignment operator */
echo "Result(SUM): $sum";
echo "<img src='math.jpg' alt='math' height='200' width='200'>";
echo "<h2>If val1 : $val1, what is val2</h2>";
echo "<form method = 'post'><input type='text' id='val2' name='val2' onChange='preventDefault();validateForm();'></form>";
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
echo ('The Value You Choose Was: ' . $_POST['val2'] . '<br/>');
$_SESSION['value2'] = $val2;
if ($_POST['val2'] == $val2 && isset($_POST['val2'])) {
echo 'You Answered Correctly';
} elseif(isset($_POST['val2'])) {
echo ('Wrong the correct answer was: ' . $_SESSION['value2']);
}
}
?>
The problem is that you are regenerating $val1 and $val2 again before checking their response.
Lets say, on the first page load $val1 = 1 and $val2 = 2.
The screens should say something akin to 1 + ? = 3.
The user (correctly) answers 2 and submits the form. PHP starts from square one every time you run the script - so the first thing it'll do is generate $val1 = 5 and $val2 = 3. This has changed the answer. It is no longer correct.
So basically you need to save $val1 and $sum in your form (possibly as hidden fields) so that you can reference them when checking the answers. When the REQUEST_METHOD is POST - read from those instead of generating new ones.
As you might already imagine, your program needs to remember the values of the random numbers between the two requests. To achieve this, you can use session varibales. A session variable can be accessed during multiple requests, until the session expires.
http://php.net/manual/en/session.examples.basic.php
You already assing the result of your game to a session variable:
$_SESSION['value2'] = $val2;
But thats not enough:
start the session with session_start();
in your if comparison, use the session variable (so you compare to the value of the previous request) instead of the newly created value
assign the session variable after your if comparison (otherwise the session variable would have the new random nubmer instead of the previous one)
Final code (untested):
<?php
session_start();
echo "<h2 id='heading'>php program to add two numbers...</h2><br />";
$val1 = rand(1, 100);
$val2 = rand(1, 100);
$sum = $val1 + $val2; /* Assignment operator */
echo "Result(SUM): $sum";
echo "<img src='math.jpg' alt='math' height='200' width='200'>";
echo "<h2>If val1 : $val1, what is val2</h2>";
echo "<form method = 'post'><input type='text' id='val2' name='val2' onChange='preventDefault();validateForm();'></form>";
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
echo ('The Value You Choose Was: ' . $_POST['val2'] . '<br/>');
if (isset($_POST['val2']) && $_POST['val2'] == $_SESSION['value2']) {
echo 'You Answered Correctly';
} elseif(isset($_POST['val2'])) {
echo ('Wrong the correct answer was: ' . $_SESSION['value2']);
}
}
$_SESSION['value2'] = $val2;

Unable to get entire string value to POST or GET to search bar only first word will apear

So, I have created a dynamic list of links from an sql query. this all works fine, however when the link is clicked I want to pass the string value of the link through a Get/Post variable into a search bar.
I can get this all to work but for some reason only the first word of the string value is being sent. for example a link "This is the Link" once clicked will only pass "This" to the search bar. I have looked around and have a feeling it has something to do with with the ' " positions.
$num=1;
if( $row_cnt = $print->num_rows >= 1 ) {
while( $arr = $print->fetch_array(MYSQLI_ASSOC)) {
print( "<tr>\r\n" );
foreach( $arr as $key=>$value) {
/*These statements ensure author is printed on one line*/
if($num == 1)
{
print( "<td><a href =".$rootPath."search/master_page_search.php?key='".$value."' >".$value."</a> </td>\r\n" );
$num=2;
}
else
{
print( "</br><td><a href =".$rootPath."search/master_page_search.php?key=".$value." >".$value."</a><br/> </td>\r\n" );/*---These are the lines the value is being sent from It is printed correctly but $value only sends the first word in the $GET_['key']*/
$num=1;
}
}
print( "</tr>\r\n " );
The PHP then puts the value into the search bar by placing the $_GET['key] into the search bars value.
if(isset($_GET['key']))
{
echo $_GET["key"];
}
The links display correctly with the entire string however the value only contains a single word value...
Another way of making it works is to surround the $value between '' and "" ej:
echo "<option value=" . "'$row[1]'" . ">" . $row[1] . "</option>";
OR
echo '<option value=' . "'$row[1]'" . '>' . $row[1] . '</option>';
This line is showing inside the selector the String, for example, "Hello World" and
sending "'$row[1]'", note the double pair of "''", in both cases are the same.

PHP String that is equal to $_POST will not change later, or maybe it is something else

I've been learning PHP in my spare time, and this is one of my "Hello, World" type scripts I'm doing for practice.
This is the code below, and the default strings will not change so the code will end up looping into eternity for I have no idea why:
<?php
if (isset($_POST["pbankroll"], $_POST["pstartbet"]))
{
$bankroll = $_POST["pbankroll"];
$startBet = $_POST["pstartBet"];
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>
The form to it:
<form action="index.php" method="post">
Bankroll: <input type="text" name="pbankroll">
Start Bet: <input type="text" name="pstartbet">
<input type="submit">
</form>
I appreciate the help.
The HTML name pstartbet needs to be changed to pstartBet.
Edit to clarify:
The Start Bet input element in the HTML form has the name pstartbet with the 'B' in lowercase. When PHP checks for that value, it's looking for pstartBet with the B capitalized. One of these two names needs to be changed so the cases match.
As it is:
$startBet = $_POST["pstartBet"]; // doesn't exist
This means that $startBet will be null. When cast to a number by the mathematical operations this will result in 0 - so the value of $bankroll will never change, and the loop will continue forever.
First, you'll have to convert the incoming values to integer before using them in numerical operations:
$bankroll = intval($_POST["pbankroll"]);
$startBet = intval($_POST["pstartBet"]);
Or if they are float values use:
$bankroll = floatval($_POST["pbankroll"]);
$startBet = floatval($_POST["pstartBet"]);
Beside from this, the code can of course run forever. This is because of the pseudo randum numbers that are being used. If over a long time there are more 1's then 0's generated by mat_rand() then the code will run forever
Consider that truly random numbers cannot be generated by a computer. Apparently mt_rand generates a pseudo-random number in such a way that it's causing an infinite loop.
I would recommend setting the variables outside of the if clause & setting a default of '' which basically means 'empty' & then having the if check if those two variables are empty or not.
<?php
$bankroll = array_key_exists("pbankroll", $_POST) ? intval($_POST["pbankroll"]) : '';
$startBet = array_key_exists("pstartbet", $_POST) ? intval($_POST["pstartbet"]) : '';
if (!empty($bankroll) && !empty($startBet))
{
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>

Using PHP if condition inside HTML code

I am using HTML inside PHP like this.
for($i=0;$i<count($arrSql);$i++)
$opt.="<option". if($_GET['pId'] == $arrSql[$i][0]){ echo "Selected";} ."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";
I have tested it for a long time and it looks correct, but it is showing an error and I don't know where the bug is.
You can't use concatenation and if together. Change it to:
for ($i=0;$i<count($arrSql);$i++) {
$opt .= "<option"
. ($_GET['pId'] == $arrSql[$i][0] ? " selected" : '')
."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";
You forgot the spaces.
Try following:
for($i=0;$i<count($arrSql);$i++)
$opt.="<option". ($_GET['pId'] == $arrSql[$i][0] ? ' selected="selected" ' : ' ') ."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";
Your echo call is not needed in this place. Your statement only concatenates strings and does not print them.
Additionaly it's not possible to use an if statement inside a string concatenation. However the if shortcut, the so called ternary operator is applicable in this situation.
And as pointed out in an other answer there is also a space missing before the selected part.
for($i=0;$i<count($arrSql);$i++) {
$opt .= "<option "
.($_GET['pId'] == $arrSql[$i][0]) ? "Selected" : ""
."value=" .$arrSql[$i][0]
. ">" .$arrSql[$i][1]. "</option>";
}
An alternative using if that might be more clear is:
for($i=0;$i<count($arrSql);$i++){
$opt .="<option ";
if ($_GET['pId'] == $arrSql[$i][0]){
$opt .= "Selected";
}
$opt .= "value=" .$arrSql[$i][0]. ">" .$arrSql[$i][1]. "</option>";
}
If you want to, you can even inline the array accesses into the string by using curly braces leading to this last line: (more here)
$opt .= "value=${$arrSql[$i][0]}>${$arrSql[$i][1]}</option>";
For the future you might want to enable error output in your scripts. This would have indicated the main error.

Beginner if statement help

if ($row['active'] == 1) echo ''.htmlspecialchars($row['username']).''; else echo htmlspecialchars($row['username']);
Could I write this shorter and cleaner somehow?
echo $row['active'] == 1 ? ''.htmlspecialchars($row['username']).'' : htmlspecialchars($row['username']);
explained a little here http://www.addedbytes.com/php/ternary-conditionals/
I'm assuming you made a mistake putting the $id in a single quoted string, and meant for php to put the value of $id in its place in there.
$name=htmlspecialchars($row['username']);
if($row['active'] == 1) {
echo "<a href='prof?id=$id'>$name</a>";
} else {
echo $name;
}
You could take advantage of the ternary operator:
echo ($row['active'] == 1)
? ''.htmlspecialchars($row['username']).''
: htmlspecialchars($row['username'])
;
(I split the code onto separate lines for the sake of formatting.

Categories