/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] PHP test?

No that the test where you test the scripting, I am talking about is it possible to make a test using php. by that I mean, a ‘user’ fills out a form, a simple ABC type test. then the script checks for the right answer, how would you go about making a script like that, which checks if the right answer is put in and such, can you point me in the right direction, or link some kind of article about this, I looked all over the web and coudn’t find anything, so I cam here because the people on here are really good, friendly and know what they are doing.

to post a comment
PHP

21 Comments(s)

Copy linkTweet thisAlerts:
@PierceMooreJul 23.2009 — Are you just trying to compare a user's input to a pre-determined answer?

If so, try this:

[code=php]
if(isset($_POST['submit'])) {
$input = addslashes(strtolower($_POST['fieldtocheck']));
if(strcmp($input,'what_you_want_the_field_to_be_') == 0) {
// Success!
} else {
// Failure!
}
}
[/code]


The strtolower() function in there makes the field case-insensitive, and addslashes() is obviously to secure the form.

Let me know how that works for you!


Pierce
Copy linkTweet thisAlerts:
@UAL225authorJul 23.2009 — Ok thanks I will work with this, I have about 15 fields to do this to, and I want it to come up with a percentage of right should be good now thanks!
Copy linkTweet thisAlerts:
@MindzaiJul 23.2009 — Are you just trying to compare a user's input to a pre-determined answer?

If so, try this:

[code=php]
if(isset($_POST['submit'])) {
$input = addslashes(strtolower($_POST['fieldtocheck']));
if(strcmp($input,'what_you_want_the_field_to_be_') == 0) {
// Success!
} else {
// Failure!
}
}
[/code]


The strtolower() function in there makes the field case-insensitive, and addslashes() is obviously to secure the form.

Let me know how that works for you!


Pierce[/QUOTE]


You can use strcasecmp and avoid the strtolower, and add_slashes doesn't add any value in this instance, it's just introducing a bug. Any answer containing a quote is never going to match even if the user enters the correct answer. The reason for escaping quotes on user input is to protect against SQL injection, it's not a one-size-fits-all approach to securing input data. Each situation requires different techniques.

For a simple, static quiz, I use something like this, otherwise i'd use a database (untested!):

[code=php]
<?php
$questions = array(
'q1' => 'answer one',
'q2' => 'answer two',
'q3' => 'answer three',
'q4' => 'answer four',
'q5' => 'answer five',
// etc
);

if (isset($_POST['questions'])) {
$correct = 0;
foreach ($_POST['questions'] as $question => $answer) {
if (array_key_exists($question, $questions)) {
if (strcasecmp($questions[$question], $answer) === 0) {
$correct++;
}
}
}
$percentage = ($correct / sizeof($questions)) * 100;
echo "<p>You got $percentage&#37; correct!</p>";
}

?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<?php for ($i=1; $i<=15; $i++): ?>
<input type="text" name="questions[q<?php echo $i ?>]" />
<?php endfor ?>
</form>[/code]
Copy linkTweet thisAlerts:
@UAL225authorJul 23.2009 — so let me look at this: here is one qustion out of 15:
[code=html]<p>4) During an approach to a stall, an increase load factor will cause the airplane to? <br/>
<input type="radio" name="4" id="4a" value="4a" />A) Stall at a higher speed <br/>
<input type="radio" name="4" id="4b" value="4b" />B) Have a tendency to spin <br/>
<input type="radio" name="4" id="4c" value="4c" />C) Be more difficult to control</p>
[/code]


now the answer is A the first one so in the array it would look something like this:?
[code=php]'q4' => '4a',[/code] since the value and ID of the right answer are 4a.

then this
[code=php]if (isset($_POST['questions'])) {
$correct = 0;
foreach ($_POST['questions'] as $question => $answer) {
if (array_key_exists($question, $questions)) {
if (strcasecmp($questions[$question], $answer) === 0) {
$correct++;[/code]


I complete don't understand, if you can explain a bit more that would be great thanks!
Copy linkTweet thisAlerts:
@MindzaiJul 23.2009 — so let me look at this: here is one qustion out of 15:
[code=html]<p>4) During an approach to a stall, an increase load factor will cause the airplane to? <br/>
<input type="radio" name="4" id="4a" value="4a" />A) Stall at a higher speed <br/>
<input type="radio" name="4" id="4b" value="4b" />B) Have a tendency to spin <br/>
<input type="radio" name="4" id="4c" value="4c" />C) Be more difficult to control</p>
[/code]


now the answer is A the first one so in the array it would look something like this:?
[code=php]'q4' => '4a',[/code] since the value and ID of the right answer are 4a.
[/quote]


Yes, that's correct, except you need to be sure to name the fields correctly. It should be:

[code=html]<p>4) During an approach to a stall, an increase load factor will cause the airplane to? <br/>
<input type="radio" name="questions[q4]" id="4a" value="4a" />A) Stall at a higher speed <br/>
<input type="radio" name="questions[q4]" id="4b" value="4b" />B) Have a tendency to spin <br/>
<input type="radio" name="questions[q4]" id="4c" value="4c" />C) Be more difficult to control</p>
[/code]



then this

...

I complete don't understand, if you can explain a bit more that would be great thanks![/QUOTE]


See the comments below. Again be aware I wrote that code off the top of my head, I didn't test it, just trying to give you an idea of one way to go about it, so there may be errors!

[code=php]
// checks if the form has been submitted - nothing to do otherwise
if (isset($_POST['questions'])) {
// initialize the variable which will contain the number of correct answers
$correct = 0;
// since the fields in the form were named with square brackets [], they
// will be placed into an array. This line loops over each item in this array.
// So effectively this loops over every answer received.
foreach ($_POST['questions'] as $question => $answer) {
// this is just a quick check to make sure we actually have an answer for
// the current question. If it isn't in the question/answer array defined above,
// the answer is skipped. In general use this should never happen, but
// defensive coding never hurt anyone!
if (array_key_exists($question, $questions)) {
// this actually checks the answer. It compares the answer given by the
// user ($answer) to the correct answer stored in the $questions array.
// The check is done in a case insensitive manner.
if (strcasecmp($questions[$question], $answer) === 0) {
// they got the question right, increase the counter of correct answers.
$correct++;
}
}
}
$percentage = ($correct / sizeof($questions)) * 100;
echo "<p>You got $percentage&#37; correct!</p>";
}[/code]
Copy linkTweet thisAlerts:
@UAL225authorJul 23.2009 — Hey thanks so much, I figured it out, and based it off your code. But there is this issue, I ran through the test guessing and it came out to be so &#37;error, but when I went through it with all the correct answers i got an percentage of:

You got 93.3333333333% correct!

why did it not come out to be 100%?
Copy linkTweet thisAlerts:
@MindzaiJul 23.2009 — Without seeing the exact code you used it's hard to say.
Copy linkTweet thisAlerts:
@UAL225authorJul 23.2009 — When I said I used your code I meant it. Here is what I got,

[code=php]<?php
$questions = array(
'q1' => '1a',
'q2' => '2b',
'q3' => '3a',
'q4' => '4a',
'q5' => '5c',
'q6' => '5a',
'q7' => '7c',
'q8' => '8a',
'q9' => '9a',
'q10' => '10b',
'q11' => '11b',
'q12' => '12b',
'q13' => '13c',
'q14' => '14b',
'q15' => '15c',
);

// checks if the form has been submitted - nothing to do otherwise
if (isset($_POST['questions'])) {
// initialize the variable which will contain the number of correct answers
$correct = 0;
// since the fields in the form were named with square brackets [], they
// will be placed into an array. This line loops over each item in this array.
// So effectively this loops over every answer received.
foreach ($_POST['questions'] as $question => $answer) {
// this is just a quick check to make sure we actually have an answer for
// the current question. If it isn't in the question/answer array defined above,
// the answer is skipped. In general use this should never happen, but
// defensive coding never hurt anyone!
if (array_key_exists($question, $questions)) {
// this actually checks the answer. It compares the answer given by the
// user ($answer) to the correct answer stored in the $questions array.
// The check is done in a case insensitive manner.
if (strcasecmp($questions[$question], $answer) === 0) {
// they got the question right, increase the counter of correct answers.
$correct++;
}
}
}
$percentage = ($correct / sizeof($questions)) * 100;
echo "<p>You got $percentage% correct!</p>";
}
?>[/code]

Could it be that I also have two feilds for username and e-mail in the form which I am going to use to update the sql database with their score? But I didnt input them to test question array. But they are in the same <form>tag.
Copy linkTweet thisAlerts:
@MindzaiJul 23.2009 — Can you post your form code too? I'm guessing you have a typo in one of the name attributes. I just sent a manual post request and got 100&#37; so the code is working OK.
Copy linkTweet thisAlerts:
@UAL225authorJul 23.2009 — here is the entire form, I think this is all you need and dont need the rest of the html from the page its self...
[code=html]<form action="form4.php" method="post">

<p><label for="uname">Enter your Username:</label>
<input type="text" name="uname" id="uname"/></p>

<p><label for="email">Please enter the email address you used to sign up:</label>
<input type="text" name="email" id="email"/></p>

<h2>Chicago Aviation's <acronym title="Basic Airman Knowledge Test">BAKT</acronym></h2>

<p>1) What is the purpose of the rudder on an airplane? <br/>
<input type="radio" name="questions[q1]" id="1a" value="1a" />A) To control Yaw <br/>
<input type="radio" name="questions[q1]" id="1b" value="1b" />B) To control overbanking tendency <br/>
<input type="radio" name="questions[q1]" id="1c" value="1c" />C) To control roll</p>

<p>2) Which basic flight maneuver increases the load factor on an airplane as compared to straight and level flight?
<br/>
<input type="radio" name="questions[q2]" id="2a" value="2a" />A) Climbs <br/>
<input type="radio" name="questions[q2]" id="2b" value="2b" />B) Turns <br/>
<input type="radio" name="questions[q2]" id="2c" value="2c" />C) Stalls</p>

<p>3) What force makes an airplane turn? <br/>
<input type="radio" name="questions[q3]" id="3a" value="3a" />A) The horizontal component of lift <br/>
<input type="radio" name="questions[q3]" id="3b" value="3b" />B) The Vertical Component of lift <br/>
<input type="radio" name="questions[q3]" id="3c" value="3c" />C) Centrifugal force</p>

<p>4) During an approach to a stall, an increase load factor will cause the airplane to? <br/>
<input type="radio" name="questions[q4]" id="4a" value="4a" />A) Stall at a higher speed <br/>
<input type="radio" name="questions[q4]" id="4b" value="4b" />B) Have a tendency to spin <br/>
<input type="radio" name="questions[q4]" id="4c" value="4c" />C) Be more difficult to control</p>

<p>5) Which four flight fundamentals are involved in maneuvering an aircraft? <br/>
<input type="radio" name="questions[q5]" id="5a" value="5a" />A) Power, pitch, bank, and trim <br/>
<input type="radio" name="questions[q5]" id="5b" value="5b" />B) Starting, taxiing, takeoff, and landing <br/>
<input type="radio" name="questions[q5]" id="5c" value="5c" />C) Straight-and-level turns, turns, climbs, and descents</p>

<p>6) What is the purpose of wing flaps? <br/>
<input type="radio" name="questions[q6]" id="6a" value="6a" />A) To enable the pilot to make steeper approaches without gaining too much airspeed <br/>
<input type="radio" name="questions[q6]" id="6b" value="6b" />B) To relieve the pilot from constant control maintenance <br/>
<input type="radio" name="questions[q6]" id="6c" value="6c" />C) To decrease wing area to vary the lift</p>

<p>7) Wing tip vertices are created only when an aircraft is? <br/>
<input type="radio" name="questions[q7]" id="7a" value="7a" />A) Operating at high airspeeds <br/>
<input type="radio" name="questions[q7]" id="7b" value="7b" />B) Heavily loaded <br/>
<input type="radio" name="questions[q7]" id="7c" value="7c" />C) Developing lift</p>

<p>8) Applying carburetor heat will? <br/>
<input type="radio" name="questions[q8]" id="8a" value="8a" />A) Result in more air going through the carburetor <br/>
<input type="radio" name="questions[q8]" id="8b" value="8b" />B) Enrich the fuel/air mixture <br/>
<input type="radio" name="questions[q8]" id="8c" value="8c" />C) Not affect the fuel/air mixture</p>

<p>9) Which condition would cause the altimeter to indicate a lower altitude than true altitude? <br/>
<input type="radio" name="questions[q9]" id="9a" value="9a" />A) Colder than standard air temperature <br/>
<input type="radio" name="questions[q9]" id="9b" value="9b" />B) Warmer than standard air temperature <br/>
<input type="radio" name="questions[q9]" id="9c" value="9c" />C) When density altitude is higher than indicated altitude</p>

<p>10) Which aircraft has the right-of-way over all other air traffic? <br/>
<input type="radio" name="questions[q10]" id="10a" value="10a" />A) A balloon <br/>
<input type="radio" name="questions[q10]" id="10b" value="10b" />B) An aircraft in distress <br/>
<input type="radio" name="questions[q10]" id="10c" value="10c" />C) An Aircraft on final approach to land</p>

<p>11) The final authority as to the operation of the aircraft lies with the? <br/>
<input type="radio" name="questions[q11]" id="11a" value="11a" />A) Federal Aviation Administration <br/>
<input type="radio" name="questions[q11]" id="11b" value="11b" />B) Pilot in Command <br/>
<input type="radio" name="questions[q11]" id="11c" value="11c" />C) Aircraft Manufacturer</p>

<p>12) What minimum flight visibility is required for VFR flight on an airway below 10,000 feet MSL? <br/>
<input type="radio" name="questions[q12]" id="12a" value="12a" />A) 1,000 ft <br/>
<input type="radio" name="questions[q12]" id="12b" value="12b" />B) 2,000 ft <br/>
<input type="radio" name="questions[q12]" id="12c" value="12c" />C) 1,500 ft</p>

<p>13) What does the acronym VFR stand for? <br/>
<input type="radio" name="questions[q13]" id="13a" value="13a" />A) Visual Flight Regulations <br/>
<input type="radio" name="questions[q13]" id="13b" value="13b" />B) Vertical Flight Regulations <br/>
<input type="radio" name="questions[q13]" id="13c" value="13c" />C) Visual Flight Rules</p>

<p>14) An airport's rotating beacon operated during daylight hours indicates? <br/>
<input type="radio" name="questions[q14]" id="14a" value="14a" />A) There are obstructions on the airport <br/>
<input type="radio" name="questions[q14]" id="14b" value="14b" />B) The weather at the airport located in class D airspace id below basic VFR minimums. <br/>
<input type="radio" name="questions[q14]" id="14c" value="14c" />C) The air traffic control tower is not in operation</p>

<p>15) Which of the following is the chief aircraft manufacturer in each and every aspect? <br/>
<input type="radio" name="questions[q15]" id="15a" value="15a" />A) Lockheed Martin <br/>
<input type="radio" name="questions[q15]" id="15b" value="15b" />B) Airbus (this is not the answer) <br/>
<input type="radio" name="questions[q15]" id="15c" value="15c" />C) BOEING</p>

<input type="submit" value="Submit" name="Submit" />
</form>
[/code]
Copy linkTweet thisAlerts:
@MindzaiJul 23.2009 — OK the form is fine. The problem is in the $questions array:

[code=php]'q6' => '5a',[/code]
Copy linkTweet thisAlerts:
@UAL225authorJul 23.2009 — ok damn, so stupid, thanks!
Copy linkTweet thisAlerts:
@UAL225authorJul 24.2009 — Well I must say, I am proud of my self because the script works the way it is supposed to do. But I get this:

Warning: Cannot use a scalar value as an array in /home2/chicagt7/public_html/members/form4.php on line 57

I dont know what I did wrong, but the script executes successfully because it even updates the db?.
[code=php]<?php
$questions = array(
'q1' => '1a',
'q2' => '2b',
'q3' => '3a',
'q4' => '4a',
'q5' => '5c',
'q6' => '6a',
'q7' => '7c',
'q8' => '8a',
'q9' => '9a',
'q10' => '10b',
'q11' => '11b',
'q12' => '12b',
'q13' => '13c',
'q14' => '14b',
'q15' => '15c',
);

// checks if the form has been submitted - nothing to do otherwise
if (isset($_POST['questions'])) {
// initialize the variable which will contain the number of correct answers
$correct = 0;
// since the fields in the form were named with square brackets [], they
// will be placed into an array. This line loops over each item in this array.
// So effectively this loops over every answer received.
foreach ($_POST['questions'] as $question => $answer) {
// this is just a quick check to make sure we actually have an answer for
// the current question. If it isn't in the question/answer array defined above,
// the answer is skipped. In general use this should never happen, but
// defensive coding never hurt anyone!
if (array_key_exists($question, $questions)) {
// this actually checks the answer. It compares the answer given by the
// user ($answer) to the correct answer stored in the $questions array.
// The check is done in a case insensitive manner.
if (strcasecmp($questions[$question], $answer) === 0) {
// they got the question right, increase the counter of correct answers.
$correct++;
}
}
}
$percentage = ($correct / sizeof($questions)) * 100;

//stes connection to db
require ("../dbconnect.php");

$errorMessage = "";

//get the vars
$username= mysql_real_escape_string ($_POST['uname']);
$email = mysql_real_escape_string ($_POST['email']);

//check to see data and input
$query = "SELECT email FROM users WHERE gid='$username'";
$result = mysql_query($query);

if($result['email'] =! $email) $errorMessage .= "There is no email that matches your account!.<br/>";

if(empty($errorMessage))
{

$query = "UPDATE users SET Ptest = $percentage WHERE email='$email'";
mysql_query($query) OR die(mysql_error());
echo 'Your test results were entered successfully! <br/>
an instructor will contact you shortly with a date for your first lesson.';
}
else
{
echo $errorMessage;
}}
?>[/code]
Copy linkTweet thisAlerts:
@MindzaiJul 24.2009 — Your issue is that $result contains a resource, not an array, so $result['email'] is invalid. You probably want to replace it with something like this:

[code=php]
//check to see data and input
if(!mysql_num_rows($result)) $errorMessage .= "There is no email that matches your account!.<br/>";[/code]
Copy linkTweet thisAlerts:
@MindzaiJul 24.2009 — Also I made a couple of suggested changes below along with the reasoning:

[code=php]
//stes connection to db
require ("../dbconnect.php");

// no need to create a new variable, just store it back into itself.
// Less variables = less chance for things to go wrong!
$_POST['uname'] = mysql_real_escape_string($_POST['uname']);

//check to see data and input
$query = "SELECT email FROM users WHERE gid='{$_POST['uname']}' LIMIT 1";
// check the result of the query - if it doesn't work there's no point continuing.
if ($result = mysql_query($query)) {
if (!mysql_num_rows($result)) {
echo 'There is no email that matches your account!.<br/>';
} else {
// I changed this query to use the gid in the previous query. If gid uniquely ids a
// user there is no need for anything else to be used. If you keep things consistent
// it's easier to spot errors.
$query = "UPDATE users SET Ptest = $percentage WHERE gid='{$_POST['uname']}'";
// again be sure to check the result of the query - and it's best not to give error
// codes on production sites - the less info you expose the better.
if ($result = mysql_query($query)) {
echo 'Your test results were entered successfully! <br/>
an instructor will contact you shortly with a date for your first lesson.';
}
}
}

[/code]
Copy linkTweet thisAlerts:
@UAL225authorJul 24.2009 — Yea nice, I like the simpler code, but now it throws this error out, when I incorporated your changes...


Parse error: syntax error, unexpected $end in /home2/chicagt7/public_html/members/form4.php on line 70

[code=php]<?php
$questions = array(
'q1' => '1a',
'q2' => '2b',
'q3' => '3a',
'q4' => '4a',
'q5' => '5c',
'q6' => '6a',
'q7' => '7c',
'q8' => '8a',
'q9' => '9a',
'q10' => '10b',
'q11' => '11b',
'q12' => '12b',
'q13' => '13c',
'q14' => '14b',
'q15' => '15c',
);

// checks if the form has been submitted - nothing to do otherwise
if (isset($_POST['questions'])) {
// initialize the variable which will contain the number of correct answers
$correct = 0;
// since the fields in the form were named with square brackets [], they
// will be placed into an array. This line loops over each item in this array.
// So effectively this loops over every answer received.
foreach ($_POST['questions'] as $question => $answer) {
// this is just a quick check to make sure we actually have an answer for
// the current question. If it isn't in the question/answer array defined above,
// the answer is skipped. In general use this should never happen, but
// defensive coding never hurt anyone!
if (array_key_exists($question, $questions)) {
// this actually checks the answer. It compares the answer given by the
// user ($answer) to the correct answer stored in the $questions array.
// The check is done in a case insensitive manner.
if (strcasecmp($questions[$question], $answer) === 0) {
// they got the question right, increase the counter of correct answers.
$correct++;
}
}
}
$percentage = ($correct / sizeof($questions)) * 100;

//starts connection to db
require ("../dbconnect.php");

// no need to create a new variable, just store it back into itself.
// Less variables = less chance for things to go wrong!
$_POST['uname'] = mysql_real_escape_string($_POST['uname']);

//check to see data and input
$query = "SELECT email FROM users WHERE gid='{$_POST['uname']}' LIMIT 1";
// check the result of the query - if it doesn't work there's no point continuing.
if ($result = mysql_query($query)) {
if (!mysql_num_rows($result)) {
echo 'There is no email that matches your account!.<br/>';
} else {
// I changed this query to use the gid in the previous query. If gid uniquely ids a
// user there is no need for anything else to be used. If you keep things consistent
// it's easier to spot errors.
$query = "UPDATE users SET Ptest = $percentage WHERE gid='{$_POST['uname']}'";
// again be sure to check the result of the query - and it's best not to give error
// codes on production sites - the less info you expose the better.
if ($result = mysql_query($query)) {
echo 'Your test results were entered successfully! <br/>
an instructor will contact you shortly with a date for your first lesson.';
}
}
}
?>[/code]


Thats the entire code...you tell me.
Copy linkTweet thisAlerts:
@UAL225authorJul 24.2009 — Never mind, It was missing a curly brace ? anyways I think there may be an issue here, it throws out the error of, "[I]There is no email that matches your account![/I]". even though the email exists? Why does it do that?
Copy linkTweet thisAlerts:
@MindzaiJul 24.2009 — Hmmmm. Can you post the output of the following (just add it to the end of the script before the closing ?>):

[code=php]echo sprintf('<pre>&#37;s</pre>', print_r($_POST, true));[/code]

Can you also paste the corresponding 'gid' field as it appears in the database?
Copy linkTweet thisAlerts:
@UAL225authorJul 24.2009 — you want the value of the gid feild or what?

here is the output,

Array

(

[uname] => UAL225

[email] => [email protected]

[questions] => Array

(

[q1] => 1c

)

[Submit] => Submit
)
Copy linkTweet thisAlerts:
@UAL225authorJul 24.2009 — Feild=gid

Type=varchar(25)

Collation=latin1_swedish_ci

Null=No

but I think the promblem lies in that I am trying to compare it to GID wich is not what Username your putting in the form, in the form your inputting your uname, I will change that and see what happens
Copy linkTweet thisAlerts:
@UAL225authorJul 24.2009 — Yea that was it, it was comparing the wrong field with the input, thanks!
×

Success!

Help @UAL225 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...