how to show the correct result of the quiz - php

I m trying to make a quiz.It's working but not giving the right result. On a correct answer for example answer 1 variable rans should be incremented by one but it is incrementing after submitting the 2nd question, that's why the value of the 10th current answer is not including in the total correct answer.
<?php
require_once("global.inc.php");?>
<form name="test" method="post" action="test.php">
<?php
$qid=(!isset($_POST['q_id'])) ? 0 : $_POST['q_id'];
$rans=(!isset($_POST["rans"])) ? 0 : $_POST["rans"];
$totalquestion=(!isset($_POST["totalquestion"])) ?
0 : $_POST["totalquestion"];
echo $rans;
if(isset($_POST["submit"]))
{
echo "<table align='center' style='border:1px solid silver' width='80%'
bgcolor='green'>";
echo "<tr><td>Total Question Attempt</td><td>",$totalquestion,"</td><tr>";
echo "<tr><td>Correct Answer</td><td>",$rans,"</td></tr>";
echo "<tr><td>Wrong Answer</td><td>",$totalquestion-$rans,"</td></tr>";
echo "<tr><td>Correct Answer Percentage</td> <td>",$rans/$totalquestion*100,"%</td></tr>";
echo "<tr><td>Wrong Answer Percenntage</td><td>",($totalquestion-$rans)/$totalquestion*100,"%</td></tr>";
echo "</table><br><br>";
$query="select * from questions,answers
where questions.q_id=answers.q_id";
echo "<table cellpadding='5px' align='center' style='border:1px
solid silver'>";
echo "<tr><th colspan='4' id='heading'>Online Quiz Test
Question</td></tr>";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<tr><td>",$row['q_id'],"</td><td colspan='2'>",$row['question'],"</td></tr><tr><td></td>";
echo "<td colspan='2'>A. ",$row['opt1'],"</td>";
echo "<td colspan='2'>B. ",$row['opt2'],"</td></tr>";
echo "<tr><td></td><td colspan='2'>C. ",$row['opt3'],"</td>";
echo "<td colspan='1'>D. ",$row['opt4'],"</td></tr>";
echo "<tr><td colspan='4' align='right'
style='color:orange'>Correct option is ",strtoupper($row['correct_ans']),"</td></tr>";
echo "<tr><td colspan='4' align='right'
style='color:orange'><hr></td></tr>";
}
echo "</table>";
echo "<p align='right'><a href='#' onclick='window.print()'>Print</a></p>";
echo "<div style='visibility:hidden;display:none'>";
}
?>
<form name="test" method="post" action="test.php">
<?php
if(!isset($a))
{
$a=0;
//unset($_SESSION['score']);
}
if(isset($_POST['next'])) {
$a=$_POST['a'];
$totalquestion=$_POST['totalquestion'];
if(isset($_POST['rans']))
$rans=$_POST['rans'];
}
$sql1="SELECT * FROM questions,answers
where questions.q_id=answers.q_id limit 1 offset $a";
$result=mysql_query($sql1);
$num = mysql_num_rows($result);
echo "<form method='post' action=''>";
if($result) {
while ($row = mysql_fetch_array($result))
{
$qid = $row["q_id"];
$questions = $row["question"];
$opt1 = $row["opt1"];
$opt2 = $row["opt2"];
$opt3 = $row["opt3"];
$opt4 = $row["opt4"];
$correct = $row["correct_ans"];
echo $rans;
?>
<p >Q.<?php echo $qid ?> <?php echo $questions;?></p>
<input type="radio" value="<?php echo $opt1;?>" name="choice"/><?php echo $opt1;?> <br/>
<input type="radio" value="<?php echo $opt2;?>" name="choice"/><?php echo $opt2;?><br/>
<input type="radio" value="<?php echo $opt3;?>" name="choice"/><?php echo $opt3;?><br/>
<input type="radio" value="<?php echo $opt4;?>" name="choice"/><?php echo $opt4;?><br/>
<input type="hidden" value="$answer" name="rightanswer[$qid]"/>
<?php
$b=$a+1;
$sql2="SELECT * FROM questions where q_id=$qid-1 ";
$result2=mysql_query($sql2);
while ($row2 = mysql_fetch_array($result2)) {
$ans=$row2['correct_ans'];
}
if(isset($_POST['choice'])) {
if($ans==$_POST['choice']){
//echo "<input type='hidden' name='rans' value='".($rans+1). "'>";
$rans=$rans+1;
}
else {
//echo "<input type='hidden' name='rans' value='" . $rans . "'>";
$rans=$rans;
}
}
//$query="select correct_ans from questions where q_id='$qid'";
//$result=mysql_query($query);
//while ($row = mysql_fetch_array($result)) {
//echo $row['correct_ans'];
echo "<input type='hidden' value='$b' name='a'>";
echo "<input type='hidden' value='count' name='count'>";
echo "<input type='hidden' name=qid value='$qid'>";
echo "<input type='hidden' name='totalquestion' value='".$totalquestion+1)."'>";
echo "<input type='hidden' name='rans' value='" . $rans . "'>";
echo "<input type='submit' name='next' value='next'> ";
echo "<input type='submit' name='submit' value='submit'><br><br>";
echo "</form>";
}
}
?>

Okay, your code is a bit of a mess.
You have random tautologies (like the $rans=$rans; which does absolutely nothing. If the answerer clicks "next" you're assigning $totalquestion twice. Definitely take a good, hard look and refactor this page.
But the answer to your question is probably because you're checking to see if they entered in the right answer at the bottom of the code -- after you've presented the results or the next question.
You've utilized the scripting capabilities of PHP without touching on any functions so it will evaluate top to bottom.
I'd move everything around: Move the handler for "next" to the top, underneath your default variable assignments, then put the check for right answer underneath that, then do the presentation of the next question, then the "submit"handler.
I'd break up the different units into functions for readability and reusability, also. For example, make a function to print out the specified question, make another one to validate the user entered in the right answer.

Related

how to hide and show question when run by mysql

I want to have a question that came from database (mysql) and able to answer 1 question at a time..
i was able to call the question but i have no idea on how can i make it a 1 question at a time
Here is the code
$sql = "SELECT question, answerA,answerB,answerC,answerD, correctAnswer FROM iq_question order by rand() LIMIT 20;";
$result = $conn->query($sql);
?>
<div id="first">
<label class="text-left mt-3" >Please choose the correct answer.</label><br>
<hr>
<form method="post" action="" id="form-data">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<center><h4>" .$row["question"]; "</h4></center>";
echo "<hr>";
echo "<p class='text-left'>";
echo "<input type='radio' name='question1ans' id='q1a' value='A'>";
echo "<label class='text-left' for='Q1A'>A. ".$row["answerA"];"</label></p>";
echo "<p class='text-left'>";
echo "<input type='radio' name='question1ans' id='q1b' value='B'>";
echo "<label for='Q1B'>B. ".$row["answerB"];"</label></p>";
echo "<p class='text-left'>";
echo "<input type='radio' name='question1ans' id='q1c' value='C'>";
echo "<label for='Q1C'>C. ".$row["answerC"];"</label></p>";
echo "<p class='text-left'>";
echo "<input type='radio' name='question1ans' id='q1d' value='D'>";
echo "<label for='Q1D'>D. ".$row["answerD"];"</label></p>";
echo "<p class='text-left'>";
echo "<hr>";
}
}
?> ````

PHP dynamic table

I have to make a dynamic table n*n , the user first gives the number n and the program makes a 5*5 table with check box this part I have make it, the second part is the user checks same of the checkbox and clicks on submit and the program makes again a table 5*5 but in the place of check box which checks is colored. I have uploaded and image.
Sorry for my bad English, thanks for your time.
enter image description here
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Give value">
</form>
<?php
$rows = $cols = $name = "";
if(isset($_GET['subject']))
$rows = $cols = $_GET['subject'];
if(isset($_POST['check_list']))
$name = $_POST['check_list'];
if(isset($_GET['subject'])){
echo "<form action='my.php' method='post'>";
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
for($td=1;$td<=$cols;$td++){
echo "<td><input type='checkbox' name='check_list[]' value='value ".$td."'></td>";
}
echo "<tr>";
}
echo "</table>";
echo "<input type='submit' />
</form>";
}
// this part of code is not make the third excecution the number 3 image
echo $cols;
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
foreach($_POST['check_list'] as $value){
if($tr == $value[td])echo "<td bgcolor='#FF0000'></td>";
else
echo "<td> </td>";
}
echo "</tr>";
}
echo "</table>";
?>

Database not updating in html table

i have html table which output all my database :
Edit(button)
pkg | kodsk | namask | tahun | makmal | catatan | murid | netbook
a | b | c | d | e | f | g | h
After user click edit button above table, user can change all the data in table.
My problem is, only some row can be edited. For example my database have 8 row, only row number 8 and 7 can be edit. Other row if try to change the data, nothing happen. My code is ok without any error, so i don't know where the problem is. Please someone help me,i just learn for fun.
<?php
session_start();
include("connections.php");
?>
<meta http-equiv="refresh" content="10";>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="3" style= "background-color: #84ed86; color: #761a9b; margin: 5 auto;" >
<?php
$result = $connect->query("SELECT * FROM data2017 INNER JOIN pengguna USING (pkg)
WHERE pengguna.username = '$_SESSION[username]'");
echo "<tr>";
echo "<th>pkg</th>";
echo "<th>kodsk</th>";
echo "<th>sek</th>";
echo "<th>tahun</th>";
echo "<th>makmal</th>";
echo "<th>catatan</th>";
echo "<th>murid</th>";
echo "<th>netbook</th>";
echo "</tr>";
while($row = $result->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
echo "<input type='hidden' name='bil' value='".$row['bil']."' />";
echo "<td><input type='text' name='pkg' value='".$row['pkg']."' /></td>";
echo "<td><input type='text' name='kodsk' value='".$row['kodsk']."' /></td>";
echo "<td><input type='text' name='namask' value='".$row['namask']."' /></td>";
echo "<td><input type='text' name='tahun' value='".$row['tahun']."' /></td>";
echo "<td><input type='text' name='makmal' value='".$row['makmal']."' /></td>";
echo "<td><input type='text' name='catatan' value='".$row['catatan']."' /></td>";
echo "<td><input type='text' name='murid' value='".$row['murid']."' /></td>";
echo "<td><input type='text' name='netbook' value='".$row['netbook']."' /></td>";
echo "</tr>";
}
echo "<input type='submit' name='update' value='UPDATE' />";
?>
</table>
</form>
<?php
if(isset($_POST['update']))
{
$bil = $_POST['bil'];
$pkg = $_POST['pkg'];
$kodsk = $_POST['kodsk'];
$namask = $_POST['namask'];
$tahun = $_POST['tahun'];
$makmal = $_POST['makmal'];
$catatan = $_POST['catatan'];
$murid = $_POST['murid'];
$netbook = $_POST['netbook'];
$sql = "UPDATE `data2017` SET `pkg`=:pkg,`kodsk`=:kodsk,`namask`=:namask,`tahun`=:tahun,`makmal`=:makmal,`catatan`=:catatan,`murid`=:murid,`netbook`=:netbook WHERE `bil`=:bil";
$stmt = $connect->prepare($sql);
$pdoExec = $stmt->execute(array(":pkg"=>$pkg,":kodsk"=>$kodsk,":namask"=>$namask,":tahun"=>$tahun,":makmal"=>$makmal,":catatan"=>$catatan,":murid"=>$murid,":netbook"=>$netbook,":bil"=>$bil));
if($pdoExec)
{
echo 'Data Updated';
}
else
{
echo 'Fail To Update';
}
}
?>
The problem is that you are not uniquely identifying each and every form element. If you have 8 rows, then you have 8 values named pkg, but there can only be one $_POST['pkg'] This is why the last row usually wins and is the only one updated.
You are going to have to add the bil field to every input name, then separate it out later.
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Source
Try this:
edit 1: I had to edit this when I realized placing $bil at the beginning of the input name would violate the statement I placed above. I moved it to the right side of the name.
edit 2: Modified my method to build the array in html like showdev taught me
<?php
session_start();
include("connections.php");
?>
<meta http-equiv="refresh" content="10";>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="3" style= "background-color: #84ed86; color: #761a9b; margin: 5 auto;" >
<?php
$result = $connect->query("SELECT * FROM data2017 INNER JOIN pengguna USING (pkg)
WHERE pengguna.username = '$_SESSION[username]'");
echo "<tr>";
echo "<th>pkg</th>";
echo "<th>kodsk</th>";
echo "<th>sek</th>";
echo "<th>tahun</th>";
echo "<th>makmal</th>";
echo "<th>catatan</th>";
echo "<th>murid</th>";
echo "<th>netbook</th>";
echo "</tr>";
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$bil = $row['bil'];
echo "<tr>";
echo "<input type='hidden' name='row[$bil][:bil]' value='$bil' />";
echo "<td><input type='text' name='row[$bil][:pkg]' value='".$row['pkg']."' /></td>";
echo "<td><input type='text' name='row[$bil][:kodsk]' value='".$row['kodsk']."' /></td>";
echo "<td><input type='text' name='row[$bil][:namask]' value='".$row['namask']."' /></td>";
echo "<td><input type='text' name='row[$bil][:tahun]' value='".$row['tahun']."' /></td>";
echo "<td><input type='text' name='row[$bil][:makmal]' value='".$row['makmal']."' /></td>";
echo "<td><input type='text' name='row[$bil][:catatan]' value='".$row['catatan']."' /></td>";
echo "<td><input type='text' name='row[$bil][:murid]' value='".$row['murid']."' /></td>";
echo "<td><input type='text' name='row[$bil][:netbook]' value='".$row['netbook']."' /></td>";
echo "</tr>";
}
echo "<input type='submit' name='update' value='UPDATE' />";
?>
</table>
</form>
<?php
if(isset($_POST['update']))
{
$sql = "UPDATE `data2017` SET `pkg`=:pkg,`kodsk`=:kodsk,`namask`=:namask,`tahun`=:tahun,`makmal`=:makmal,`catatan`=:catatan,`murid`=:murid,`netbook`=:netbook WHERE `bil`=:bil";
$stmt = $connect->prepare($sql);
foreach($_POST['row'] as $data)
{
$pdoExec = $stmt->execute($data);
if($pdoExec) { echo 'Data Updated'; } else { echo 'Fail To Update'; }
}
}
?>
The inputs have the same names for every row, so the row values overwrite each other and only the last row is effectively posted.
One method is to structure posted data as an array, including a row identifier to distinguish values for different rows. Ideally, the row identifier is a numeric PRIMARY index.
For reference, see How do I create arrays in a HTML <form>?
Here's an example:
while($row = $result->fetch(PDO::FETCH_ASSOC)){
echo '<tr>
<td>
<input type="text" name="row['.$row['bil'].'][pkg]" value="'.$row['pkg'].'">
</td>
<td>
<input type="text" name="row['.$row['bil'].'][kodsk]" value="'.$row['kodsk'].'">
</td>
</tr>";
}
Then you'll end up with a posted array like this:
Array
(
[row] => Array
(
[1] => Array
(
[pkg] => stuff
[kodsk] => things
)
[2] => Array
(
[pkg] => other
[kodsk] => another
)
)
)
And you can iterate through that array to update the database, something like this:
if (!empty($_POST['row'])) {
$sql = "UPDATE `data2017` SET `pkg`=:pkg, `kodsk`=:kodsk WHERE `bil`=:bil";
$stmt = $connect->prepare($sql);
foreach ($_POST['row'] as $bil => $row) {
$pdoExec = $stmt->execute(
array(":pkg"=>$row['pkg'],
":kodsk"=>$row['kodsk'],
":bil"=>$bil)
);
}
}

HTML button running out of alignment

My idea is very simple, I will have a search box and a submit button.
When user key in the keyword and click on the submit button, results will be shown below with an additional button. Now my problem is I have no idea on how to make the button to be located at bottom right of the table populated.
Please consider the below code for my situation:
<input type="text" name="criteriaInput" style="width: 300px;"> <input type="submit" name="submit" value="GO" />
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['inquiryMethod'])){
error_reporting(0);
$sql = 'SELECT
*
FROM
table
WHERE
fullname REGEXP \''.$_POST['criteriaInput'].'\'' ;
$server = mysql_connect("localhost","root", "");
$db = mysql_select_db("mysql",$server);
$query = mysql_query($sql);
echo "<table class=\"striped\">";
echo "<tr class=\"header\">";
echo "<td>Full Name</td>";
echo "<td>ID</td>";
echo "<td>ID Type</td>";
echo "<td>Issuance Country</td>";
echo "<td>Class</td>";
echo "</tr>";
while ($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>".$row[fullname]."</td>";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[id_type]."</td>";
echo "<td>".$row[issuance_country]."</td>";
echo "<td>{$row['class']}</td>";
echo "</tr>";
}
echo "<form method=\"post\" action=\"CIF_InquiryAction.php\">";
echo "<input type=\"submit\" name=\"create\" value=\"Create\" />";
echo "</form>";
echo "</table>";
}else{
echo "Please select one of the criteria!";
}
}
?>
The submit button with value "Create" did successfully created on existence of data, however it's aligned on top left of the table.
Kindly advice Thank you.
You need to put your button into a table row and cell.
echo "<tr>";
echo "<td colspan=\"5\">"
echo "<form method=\"post\" action=\"CIF_InquiryAction.php\">";
echo "<input type=\"submit\" name=\"create\" value=\"Create\" />";
echo "</form>";
echo "</td>"
echo "</tr>";
Also, your form should probably move to be outside your table.
Editing to show input outside of table:
echo "</table>";
echo "<input type=\"submit\" name=\"create\" value=\"Create\" />";

PHP - How do you select a specific index of a row given by mysqli_fetch_array()?

Please refer to the image below:
http://i.stack.imgur.com/6hBPC.png
For instance, if a user clicks the button on the row which says "You have a quiz for math", the "Quiz ID" value of THAT row would then be passed to another PHP file.
Here's my current code:
<?php
$con=mysqli_connect("127.0.0.1", "root", "", "quizmaker");
if (mysqli_connect_errno($con))
{
echo "MySqli Error: " . mysqli_connect_error();
}
$now=date("m/d/Y");
$sql=mysqli_query($con,"SELECT * FROM quiz_query WHERE quiz_date='$now'");
$count=mysqli_num_rows($sql);
if($count>=1)
{
echo "<table border='1' width='50%'>";
echo "<form action='answer_quiz.php' method='post'>";
echo "<tr>
<td>You have a pending quiz!</td><td> </td><td> </td>
</tr>";
$number=1;
while($result=mysqli_fetch_array($sql))
{
echo "<tr>";
echo "<td>You have a quiz for " . $result['subject'] . "</td>";
echo "<td>Quiz ID: " .$result['quiz_ID']. "</td>";
echo "<td><input type='submit' name='button' id='button' value='Take Quiz'>";
echo "<input type='hidden' name='quiz[$number]' value='$result[quiz_ID]'>";
echo "</td>";
echo "</tr>";
$number++;
}
echo "</form>";
echo "</table>";
}
else
{
"You have no quiz! :D";
}
mysqli_close($con);
?>
Move this line:
echo "<form action='answer_quiz.php' method='post'>";
Inside of the while loop.
Also, change
echo "<input type='hidden' name='quiz[$number]' value='$result[quiz_ID]'>"
with
echo "<input type='hidden' name='quizId' value='$result[quiz_ID]'>"
Now, in answer_quiz.php you'll receive $_POST['quizId'] with the value you need.
Change your while to :
while( $row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['subject'];
}
You are forgetting quotes around your variable:
Instead of
echo "<input type='hidden' name='quiz[$number]' value='$result[quiz_ID]'>";
It should be
echo "<input type='hidden' name='quiz[$number]' value='$result[\"quiz_ID\"]'>";

Categories