Help with retrieving answers from radio buttons - php

$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';
mysql_connect($host,$user,$pw);
mysql_select_db($db);
$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
$array[] = $row;
}
for($i=0; $i<=($num_rows-1); $i++)
{
$title = $array[$i]['Title'];
$ans1 = $array[$i]['Answer1'];
$ans2 = $array[$i]['Answer2'];
$ans3 = $array[$i]['Answer3'];
$ans4 = $array[$i]['Answer4'];
echo $title.'<br>';
echo '<form method="post">';
echo '<input type="radio" name="ans'.$i.'">'.$ans1.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans2.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans3.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans4.'<br>';
}
echo '<input type="submit" value="submit" id="submit">';
echo '</form>';
I manage to display the question followed by the corresponding choices and at the bottom a submit button.
How would I, on click of the submit button, get the values that the user have chosen for each question that was looped out from the database? ans1, ans2, etc.
This is necessary to compare their answer to the answer key and compute their score.
.help please! Thank you very much and More power!

Assign a value to each of the radio inputs, the updated script could be:
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';
mysql_connect($host,$user,$pw);
mysql_select_db($db);
$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
$array[] = $row;
}
//Start the form
echo "<form method=\"post\" action=\"path/to/receiving.php\">\n";
for($i=0; $i<=($num_rows-1); $i++)
{
//Render a question + the answer choices
echo $array[$i]['Title']."<br />\n";
for ($j=1;$j<=4;$j++) {
echo "<input type=\"radio\" name=\"ans$i\" value=\"$j\">".
$array[$i]['Answer'.$j]."<br />\n";
}
}
//End the form
echo "<input type=\"submit\" value=\"submit\" id=\"submit\">\n</form>";
Now to read the values of the answers from within PHP:
echo $_POST["ans1"];
//The answer given for question 1, will be between
// 1-4 or null (if they didn't answer

Related

How to make a loop statement, to get the value from the previous page?

I'm setting up an online quiz/exam page in my website on localhost (for education purposes only). But when checking for the answer it only checks for the second question for the right answer.
e.g There are 2 questions. I chose both correct answers, but at the next page it shows that I got 1 out of 2. ?
I have tried using POST/GET method as well...
but still the same
Students taking the quiz (Question).php
<?php
include("conn.php");
$quiz_id = intval($_GET['quiz_id']);
$display = mysqli_query($con,"SELECT * FROM question WHERE quiz_id =
$quiz_id");
if (!isset($_POST['Submit']) || ($_POST['Submit'] != 'Mark')) {
while ($row = mysqli_fetch_array($display)) {
echo "<form method=post action='score.php?quiz_id=";
echo $row['quiz_id'];
echo "'>";
echo "<table border=0>";
$id = $row["question_id"];
$question = $row["questions"];
$opt1 = $row["option1"];
$opt2 = $row["option2"];
$opt3 = $row["option3"];
$opt4 = $row["option4"];
$answer = $row["answer"];
echo "<tr><td colspan=3><br><b>$question</b></td></tr>";
echo "
<tr>
<td>$opt1 <input type=radio name='q$id' value=\"$opt1\"></td>
<td>$opt2 <input type=radio name='q$id' value=\"$opt2\"></td>
<td>$opt3 <input type=radio name='q$id' value=\"$opt3\"></td>
<td>$opt4 <input type=radio name='q$id' value=\"$opt4\"></td>
</tr>
";
}
echo "</table>";
echo "<input type='Submit' name='Submit' value ='Mark'>";
echo "</form>";
}
?>
Score.php (marking the results)
<?php
include("conn.php");
$quiz_id = intval($_GET['quiz_id']);
if ($_POST['Submit']) {
$display = mysqli_query($con,"SELECT * FROM question WHERE quiz_id = $quiz_id");
while ($row = mysqli_fetch_array($display)) {
$id = $row["question_id"];
$answer = $row["answer"];
$score = 0;
$total = mysqli_num_rows($display);
while ($result = mysqli_fetch_array($display)) {
$answer = "$result[answer]";
$q = "q$result[question_id]";
$q = trim($q);
if ($_POST[$q] == $answer) {
$score++;
}
}
echo "<p align=center><b>You scored $score out of $total</b></p>";
echo "<p>";
}
}
?>
I expect the results to be 2 out of 2.
But it is showing only 1 out of 2.
UPDATE
<?php
include("conn.php");
$quiz_id = intval($_GET['quiz_id']);
//echo 'from form: '.$_POST['q14']; // from form
if ($_POST['Submit']) {
$display = mysqli_query($con,"SELECT * FROM question WHERE quiz_id =
$quiz_id");
while ($result = mysqli_fetch_array($display)) {
$id = $result["question_id"];
$answer = $result["answer"];
$score = 0;
$total = mysqli_num_rows($display);
$answer = $result['answer'];
$q = $result['question_id'];
echo 'answer: '.$answer;
//echo $q;
//$q = trim($q);
/* if ($q == $answer) {
$score++;
//echo "<p align=center><b>You scored $score out of $total</b></p>";
//echo "<p>";
}
}
?>

PHP Issue Updating Database On Button Click

Hello I'm making a shop in php where I populate the shop with a while loop so all the shop items from my database are displayed. This works fine but I have an issue when I try to update the stock count and money left on the account when I press the buy button.
The $ItemCost variable only saves the last populated item cost and I'm not sure how to save the cost of each item to insert it into the database.
Also the $StockCount variable sets the stockcount to 1.
How can I fix this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useraccounts";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$GatherItems = "SELECT * FROM shopitems WHERE StockCount > 0 ORDER BY`shopitems`.`Cost` DESC";
$result = $conn->query($GatherItems);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ItemName = $row['ItemName'];
$ItemCost = $row['Cost'];
$ID = $row['ID'];
$StockCount = $row['StockCount'];
$Money = $row['Money'];
echo "<div class='test'>$ItemName</div>";
echo "<div class='test1'>$ItemCost </div>";
echo "<input type='submit' class='btn btn-primary' name='Buy' value='Buy Now'/>";
}
$NewTotal = $Money - $ItemCost;
$Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money = $NewTotal WHERE ID = $ID";
if(isset($_POST['Buy'])){
if ($conn->query($Inventory) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $Inventory . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
As #Sean said, you can do this like :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useraccounts";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['Buy'])){
// update stock and money
$ID = $_POST['ID'];
$Money = $_POST['Money'];
$ItemCost = $_POST['ItemCost'];
$NewTotal = $Money - $ItemCost;
$Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money =
$NewTotal WHERE ID = $ID";
if ($conn->query($Inventory) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $Inventory . "<br>" . $conn->error;
}
}
// display items
$GatherItems = "SELECT * FROM shopitems WHERE StockCount > 0 ORDER
BY`shopitems`.`Cost` DESC";
$result = $conn->query($GatherItems);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ItemName = $row['ItemName'];
$ItemCost = $row['Cost'];
$ID = $row['ID'];
$StockCount = $row['StockCount'];
$Money = $row['Money'];
echo "<form method='post' action=''>";
echo "<div class='test'>$ItemName</div>";
echo "<div class='test1'>$ItemCost </div>";
echo "<input type='hidden' name='Id' value='".$ID."'/>";
echo "<input type='hidden' name='Money' value='".$Money."'/>";
echo "<input type='hidden' name='ItemCost' value='".$ItemCost."'/>";
echo "<input type='submit' class='btn btn-primary' name='Buy' value='Buy Now'/>";
echo "</form>";
}
}
$conn->close();
Assuming you don't want ajax, and you don't want js, but only a 'buy' button under each item which will reopen the entire page, then you want something like this. This is pseudo code:
//FIRST we need to process the form:
<?php
if(isset($_POST['submit'])){
$itemId = $_POST['id'];
//do the stuff. Remember about escaping $itemId, or using prepared statements
//select... from where id = $itemId
}
?>
//now get the items:
<?php
$GatherItems = ...
?>
//now the html:
<?php
while($row = $result->fetch_assoc()) {
?>
<form method = 'post'>
<div class='test'><?=$ItemName?></div>
...
<input type = 'hidden' name = 'itemId' value = '<?=$ID?>'>
<input type = 'submit' name = 'submit' value = 'Buy'>
</form>
}
?>

Submit button needs to be clicked twice to get my results from radio buttons in a php script

The problem with this code is that I can't read the results in $survey_Answers1 except after clicking on the submit button twice.
file:survey.php
<?PHP
session_start();
//=========================================================
//The following page is used to create a dynamic survey.
//=========================================================
$qNum = 'q1';
$question = 'Question not set';
$answerA = 'unchecked';
$answerB = 'unchecked';
$answerC = 'unchecked';
$qID = array();
$question = array();
$A = array();
$B = array();
$C = array();
$survey_Answers = array();
$survey_Answers1 = '';
//============================================
// OPEN A CONNECTION TO THE DATABASE
//============================================
$user_name = "root";
$password = "";
$database = "surveyTest";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM tblquestions";
if ($db_found) {
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="survey.php">';
for ($i = 1; $i <= 2; $i++)
{
$db_field = mysql_fetch_assoc($result);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
echo '<P>';
print $question[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'A'>";
print $A[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'B'>";
print $B[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'C'>";
print $C[$i];
if (isset($_POST[$qNum])){
$survey_Answers1 = $survey_Answers1.', '.$_POST["$qNum"];
}
//var_dump($survey_Answers1);
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
}
echo '<p>';
//$_SESSION['answers'] = $survey_Answers1;
//var_dump($_SESSION['answers']);
echo "<INPUT TYPE = 'hidden' Name = 'h2' VALUE = '".$survey_Answers1."'>";
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
var_dump($_POST['h2']);
echo '</form>';
mysql_close($db_handle);
}
else {
print "Error getting Survey";
mysql_close($db_handle);
}
?>
The value stored in var_dump($_POST['h2']); after hitting clicking the submit button once is: string '' (length=0)
P.S., using session variables doesn't resolve the problem, so please don't suggest this answer!!!!
Try to insert after for-loop
for ($i = 1; $i <= 2; $i++)
{
// your code here
}
if (empty($_POST['h2'])) $_POST['h2'] = $survey_Answers1; // insert this line
Or use JavaScript, insert to the end of file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var answers = '';
$('input[type=Radio]:checked').each(function() {
if (answers !== '') {
answers += ',';
}
answers += $(this).val();
})
$('input[name=h2]').val(answers);
});
}
})
</script>
From what I see your problem is with your for loop try to see whats returning survey_Answers1 in each loop. you can try this to see whats returning each time it loops and part from there
if (isset($_POST[$qNum])){
$survey_Answers1 = $survey_Answers1.', '.$_POST["$qNum"];
?>
<script type="text/javascript"><?php echo $survey_Answers1; ?></script>
<?php
}

Passing an array in PHP to another PHP script through html hidden form element

My question is that when I copy my array elements between different php scripts using session variables, nothing gets printed out. The following are my two php files.
file1.php
$SQL = "SELECT * FROM tblquestions";
if ($db_found) {
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="file2.php">';
for ($i = 1; $i <= 2; $i++)
{
$db_field = mysql_fetch_assoc($result);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
echo '<P>';
print $question[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'A'>";
print $A[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'B'>";
print $B[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'C'>";
print $C[$i];
//if (isset($_POST[$name_Value]))
$survey_Answers[$i-1] = $_POST[$qNum];
print '</BR>'.$survey_Answers[$i-1]."</BR>";
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
}
echo '<p>';
session_start();
$_SESSION['answers'] = $survey_Answers;
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
echo '</form>';
On my Second file (file2.php), I have the following:
<?PHP
session_start();
if (isset($_POST['Submit1'])) {
$results = $_SESSION['answers'];
print $results[0];
?>
Nothing gets printed out when executing the above code.
Thanks in advance
I am pretty sure that the session values stored need to be strings.
In file1.php change:
$_SESSION['answers'] = $survey_Answers;
to this:
$_SESSION['answers'] = json_encode($survey_Answers);
Then in file2.php change:
$results = $_SESSION['answers'];
to this:
$results = json_decode($_SESSION['answers']);

How to count the unchecked checkboxes in a while loop

$query = mysql_query("SELECT DISTINCT status, vendor FROM tbl_softwareinstalled WHERE vendor NOT LIKE ''");
$nums = mysql_num_rows($query);
echo "<form name = 'filter' action='softwarefilter.php' method='POST'>
$nums<br>
<table border = 1><tr><td> </td>
<td><strong>Software Vendor</strong></td></tr>";
$ctr1 = 1;
while($fetch = mysql_fetch_array($query)) {
$vendor = $fetch['vendor'];
$status = $fetch['status'];
if(($ctr1 % 2)==1)
{ print "<tr bgcolor = 'white'>";}
else
{ print "<tr bgcolor = '#EEEEEE'>"; }
print "<td><input name= 'chk[]' type='hidden' value='0'>
<input type = 'checkbox' name = 'chk[]' value = '$vendor' ";
if ($status == 'Enabled') {
print "checked = 'checked'></td><td>$vendor</td></tr>"; }
else {
print "></td><td>$vendor</td></tr>"; }
$ctr1++;
}
print "</table>";
print "<input type = 'submit' name = 'submit' value = 'Update Filter'>
</form> ";
$submit = $_POST['submit'];
if(isset($submit))
{
$chk = $_POST['chk'];
$count = count($chk);
if (empty($chk)) {
echo "qweqwe<br>";
}
for ($i=0; $i<$count; $i++) {
$abc = $chk[$i];
$query = mysql_query("UPDATE tbl_softwareinstalled SET status = 'Enabled' WHERE vendor = '$abc'");
}
echo '<meta http-equiv="refresh" content="0.5;url=/assets/softwarefilter.php">
<script language="javascript">
alert("Software filter updated.");
</script>';
}
Hi, how can I count the UNCHECKED CHECKBOXES in a while loop with this block of code?
Let's say for example I have 10 checkboxes with 10 values, the user checked 3 checkboxes (with values: 'abc', 'def', 'ghi'), after submitting it. It will count all the UNCHECKED checkboxes and echoes the value of it. The values of 3 checked checkboxes SHOULD NOT be echoed.
The browser will only tell you which have been checked. Pull all the possible boxes from your database, and then remove those that the browser has told you are checked.
I had worked on a similar thing for counting unchecked boxes.
place two input fields of input type checkbox and input type hidden with different names
<input type="hidden" class="" name="test[]" value="0">
<input type="checkbox" class="" name="checkbox[]" value="1">
then on submit
if (isset($_POST['submit'])) {
$cnt = array();
$counter =0;
$testcnt = 0;
$cnt = 0;
if (isset($_POST['test'])) {
$testcnt = count($_POST['test']);
}
if (isset($_POST['checkbox'])) {
$cnt = count($_POST['checkbox']);
}
echo 'the count of unchecked boxes is ';
print_r($testcnt-$cnt);
}
For your case change this to:
<input name= 'unchecked[]' type='hidden' value='0'>
then on submit when your checking for isset(submit) you can add the following an d change accordingly
$unchecked_input = count($_POST['unchecked']);
$chk = $_POST['chk'];
$count = count($chk);
echo $unchecked_input-$count; //will output the count of unchecked boxes

Categories