i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission
Problem:
So when I login, a user can go to the browse.php to add images to the favorites.php, and the photos will appear on that page.
When I log out and log back in, the images are gone (not saved).
Question:
How do I save it after I logout so on next login I get to see the favorite'd images from that particular user using cookies or other methods (can't use database because I'm not allowed to)?
My favorites page
<?php
session_start();
require_once 'favoritesfunction.php';
if (isset($_GET["fileName"])) {
$fileName = $_GET["fileName"];
addToFavorites($fileName);
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
$title = "Travel Photos - View Favorites";
?>
<link rel="stylesheet" href="viewfavorites.css" />
</head>
<body>
<main class="container">
<h1 class="favheader">Favorites</h1>
<div class="content">
<?php
if (isset($_SESSION['favorites']) && isset($_SESSION['email'])) {
$favorites = $_SESSION['favorites'];
if (count($favorites) > 0) {
?> <ul class="ul-favorite"> <?php
foreach ($favorites as $f) {
echo '<img class="displayPic" src="https://storage.googleapis.com/assignment1_web2/square150/' . $f . '">';
}
?>
</ul>
<p id="removeall"><button class="button"><span><a target="" href="services/removefavorites.php?remove=all">Remove All</a></span></button></p>
<?php
}
} else {
?>
<div class="nofavorites">
<p>No favorites found.</p>
</div>
<?php
}
?>
</div>
</main>
</body>
<script type="text/javascript" src="main.js"></script>
</html>
My add to favorites function php
<?php
function addToFavorites($fileName)
{
//Checks if the session favorites exists
if (isset($_SESSION['favorites'])) {
$favorites = $_SESSION['favorites'];
} else {
$favorites = array();
$_SESSION['favorites'] = $favorites;
}
// add item to favourites
$item = $fileName;
$match = false;
//Loop below checks for duplicates
$i = 0;
while ($i < count($favorites)) {
if ($favorites[$i] == $item) {
$favorites[$i] = $item;
$match = true;
}
$i++;
}
//if match equals false, that means its not in the favorites list of the user
//so it is added to the user's favorites array
if ($match == false) {
$favorites[] = $item;
}
$_SESSION['favorites'] = $favorites;
$_SESSION['favorites'] = $favorites;
}
My approach:
I tried doing something like setting $name = $_SESSION['email'] and $value="<img src=...>" then setcookie($name, $value) and then if(isset($_COOKIE[$value])) echo $value
I know this is totally wrong, I tried looking everywhere online to try to solve this, if I could get some help that would be great thanks!
I have a main pain where I want to modify things from the admin account
and whenever I log out of the admin account the images are not saved and it give me an undefined index error.
this is my main page php code:
<?php $src = $_SESSION['firstimgsrc'];echo "<img id='first' src='$src'>";?><!-- Direct link 1st champion -->
<?php $src1 = $_SESSION['secondimgsrc'];echo "<img id='second' src='$src1'>"; ?><!-- Direct link 2nd champion -->
<?php $src2 = $_SESSION['thirdimgsrc'];echo "<img id='third' src='$src2'>";?> <!-- Direct link 3rd champion -->
<?php $src3 = $_SESSION['forthimgsrc'];echo "<img id='forth' style='border-right: 0px;' src='$src3'>"; ?> <!-- Direct link 4th champion -->
this is the admin panel php code:
<?php
if(isset($_POST['submit'])) {
session_start();
$firstimgsrc = $_POST['firstimgsrc'];
if ($firstimgsrc == "") {
$_SESSION['firstimgsrc'] = $jk;
} else {
$_SESSION['firstimgsrc'] = $firstimgsrc;
$jk = $_SESSION['firstimgsrc'];
}
$secondimgsrc = $_POST['secondimgsrc'];
if ($secondimgsrc == "") {
$_SESSION['secondimgsrc'] = $jk1; } else {
$_SESSION['secondimgsrc'] = $secondimgsrc;
$jk1 = $_SESSION['secondimgsrc'];
}
$thirdimgsrc = $_POST['thirdimgsrc'];
if ($thirdimgsrc == "") {
$_SESSION['thirdimgsrc'] = $jk2;
} else {
$_SESSION['thirdimgsrc'] = $thirdimgsrc;
$jk2 = $_SESSION['thirdimgsrc'];
}
$forthimgsrc = $_POST['forthimgsrc'];
if ($forthimgsrc == "") {
$_SESSION['forthimgsrc'] = $jk3;
} else {
$_SESSION['forthimgsrc'] = $forthimgsrc;
$jk3 = $_SESSION['forthimgsrc'];
}
header("Location: ../egamingtv.php");
}
?>
worked, I just used unset instead of the session_destroy in my logout page
I am trying to create a PHP file each time a user registers my website. I use the following code to create the file in my register.php :
The thing is, my create file function works but the variable $data doesn't give any result. When I run that $data as a single variable in a different PHP file it still doesn't work.
What did I do wrong about setting the variable.
// STARTING to create a file
$my_file = "$username.php";
$handle = fopen("give/$my_file", 'w') or die('Cannot open file: '.$my_file);
//----------- BEGINNING OF THE PHP DATA TO WRITE TO NEW FILE ----------
$data = "<?
require('../config.inc.php');
$damned_user = $username;
if ( $_COOKIE['damn_given'] != TRUE ) {
$sql = mysql_query(\"SELECT * FROM users WHERE username='$damned_user' LIMIT 1\");
if(mysql_num_rows($sql) == 1){
$row = mysql_fetch_array($sql);
// $row['field'];
$damned_user_id = $row['id'];
if($_SESSION['id'] == $damned_user_id) {
} else {
$taken = $row['taken_damns'];
$taken_damns = $taken + 1;
$taking_sql = \"UPDATE users SET taken_damns='$taken_damns' WHERE username='$damned_user' \";
if (mysql_query($taking_sql)) {
setcookie(\"damn_given\", TRUE, time()+3600*24);
$date = date(\"Y-m-d H:i:s\");
$ip = $_SERVER['REMOTE_ADDR'];
$damns_table = \"INSERT INTO damns (id, from_ip, user_damned, when_damned) VALUES ('','$ip','$damned_user','$date') \";
if ( mysql_query($damns_table)) {
} else {
echo \"Couldn't save damn to damns table in database!\";
}
if ( $_SESSION['logged'] == TRUE ) {
$session_id = $_SESSION['id'];
$giving_sql = \"UPDATE users SET given_damns='$taken_damns' WHERE id='$session_id'\";
if ( mysql_query($giving_sql ) ) {
} else {
echo ('Error giving damn!');
}
}
}
else
{
die (\"Error taking damn!\");
}
}
} else {
die(\"Error first sql!\");
}
}
?>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<link rel=\"stylesheet\" href=\"/_common.css\" />
<link rel=\"stylesheet\" href=\"/_col_white.css\" />
<link rel=\"shortcut icon\" href=\"/favicon.ico\" /> <title>DamnIt.tk - Damned!</title>
</head>
<body>
<div id=\"main\">
<div class=\"center\"><img src=\"/_bnr_white.png\" style=\"width: 500px; height: 100px;\" alt=\"DamnIt Banner\" /></div>
<table class=\"tmid\" style=\"width: 100%;\"><tr>
<td class=\"center\" style=\"width: 25%;\">Profile</td>
<td class=\"center\" style=\"width: 25%;\">Options</td>
<td class=\"center\" style=\"width: 25%;\">Stats</td>
<td class=\"center\" style=\"width: 25%;\">Log out</td>
</tr></table> <h1>Give a Damn</h1>
<?
if ( isset($_COOKIE['damn_given'])) {
?>
<h2>You have already given a Damn to <? echo $damned_user ?> today!</h2><h3>Couldn't damn - try again tomorrow.</h3>
<?
}
elseif ( $_SESSION['id'] == $damned_user_id ) {
?>
<h2>You cannot damn yourself!</h2>
<?
} else{ ?> <h2>Damn given!</h2><h3>You have given a Damn to <? echo $damned_user ?>.</h3> <? } ?>
</div></body>
</html>";
//------- END OF PHP WHICH MUST BE WRITTEN TO NEW FILE ---------
fwrite($handle, $data);
fclose($handle);
// finished with the file
Try NOWDOC:
$data = <<<'END'
Your PHP code here
END;
This will allow for any string, without need for escaping.
However, please consider what you're doing very carefully!
Also... you wouldn't happen to be trying to rip off this site of mine, would you? http://giveadamn.co.uk/
(source: giveadamn.co.uk)
Because if so, you're doing it wrong. .htaccess, mate ;)
RewriteEngine on
RewriteRule give/(.*) give.php?user=$1 [L]
is there a way set a value for the index.php page on its first load?
i would like index.php it to load like so "index.php?subject=1" when it loads for the first time.
as this value will change as they move around in the site i don't want it to be a fixed value.
some one sugested
if(empty($_SESSION['visited'])) {
//DO STUFF
$_SESSION['visited'] = true; }
i cant seem to get that to work with my function.
find_selected_page()
function find_selected_page () {
global $current_subject;
global $current_page;
if (isset($_GET["subject"])) {
$current_subject = find_subject_by_id ($_GET["subject"]);
$current_page = find_default_post($current_subject ["id"]);
} elseif (isset($_GET["page"])) {
$current_subject = null;
$current_page = find_page_by_id ($_GET["page"]);
} else {
$current_page = null;
$current_subject = null;
}
}
index.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/session/session.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/db/dbcon.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/inc/functions.php');
$context = "public";
find_selected_page ();
?>
<html>
<head>
<title>Home</title>
<?php include($_SERVER['DOCUMENT_ROOT'].'/inc/style.php'); ?>
<body>
<?php include($_SERVER['DOCUMENT_ROOT'].'/inc/header.php'); ?>
<?php include($_SERVER['DOCUMENT_ROOT'].'/inc/nav_ribbon.php');?>
<div id="p2dbg">
<div id="p2dcontent">
<div class="p2dcontent">
<h1><?php echo htmlentities($current_subject ["menu_name"]); ?></h1><br />
<?php if ($current_page) { ?>
<p><?php echo nl2br($current_page ["content"]); ?></p><br />
<?php } else { ?>
This page does not exist! please slect a page from the menu.
<?php } ?>
</div>
</div>
<?php include($_SERVER['DOCUMENT_ROOT'].'/inc/footer.php'); ?>
</div>
</body>
</html>
Instead of setting everything to null if your value isn't passed, just assume the default value:
// Set this to the value you want as your default
define("DEFAULTSUBJECT",1);
function find_selected_page () {
global $current_subject;
global $current_page;
if (isset($_GET["subject"])) {
$current_subject = find_subject_by_id ($_GET["subject"]);
$current_page = find_default_post($current_subject ["id"]);
} elseif (isset($_GET["page"])) {
$current_subject = null;
$current_page = find_page_by_id ($_GET["page"]);
} else {
$current_subject = find_subject_by_id (DEFAULTSUBJECT);
$current_page = find_default_post($current_subject ["id"]);
}
}