I've built a form for a short-answer quiz. Each question has multiple textboxes for answer (corresponding to instruction in the question i.e. list two components, three advantages, etc.). I've designed the form as such so that the answers can be evaluated independently against a set of answers. Each question can have many answer suggestions. Here is the 'answer' table structure:
CREATE TABLE IF NOT EXISTS `answer` (
`a_id` int(10) NOT NULL AUTO_INCREMENT,
`q_id` int(10) NOT NULL,
`a_text` text NOT NULL,
`a_keyword` text NOT NULL,
PRIMARY KEY (`a_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
This is the code of the form:
<?php
session_start();
if(isset($_SESSION['tf1_sid'])){
?>
<head>
<title>Dahlia | Formative Assessment</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" name="form1" method="post" action="s_ass_result_new.php">
<h2>Short-answer Questions</h2>
<table width="590" border="0" cellpadding="2" align="center">
<?php
// db connect
include("dbconn.php");
// db query for questions
$sql_q = "SELECT q_id, q_no, q_text, q_field FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions
//$rad = 1;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
$qfield = $data_q['q_field'];
$qno = $data_q['q_no'];
echo "<tr><td width='20' align='center' valign='top'><label><br /><input name='q_no' size='1' type='hidden' value=". $data_q['q_no'] .">". $data_q['q_no'] ."</label></td>";
echo "<td><br />". $data_q['q_text'] ." (<a href='s_help.php?s_id=". $_SESSION['tf1_sid'] ."&q_id=". $data_q['q_id'] ."' target='_blank'>Help</a>)</td>";
for($rad=1;$rad<=$qfield;$rad++){
echo "<tr><td></td><td><textarea name='answer_".$rad."' cols='55' rows='2' id='textarea1'></textarea></td></tr>";
echo "<script>document.getElementById('textarea1').focus()</script>";
//$rad++;
}
}
echo "<tr></tr><tr><td></td><td><input name='Submit' type='submit' value='Submit' onClick='return confirm(\"Are you sure?\")'></td></tr>";
mysql_free_result($query_q);
include("dbconn.php");
?>
</table>
</form>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
?>
The form is displaying fine but I'm having trouble retrieving values being submitted through the text area. Below is the code to retrieve those values:
<?php
// include db connection file
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
$qno = $_POST['q_no'];
$ansspc = $_POST['q_field'];
?>
<head>
<title>Dahlia | Formative Assessment</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Answer Review</h2>
<table width="590" border="0" cellpadding="2" align="center">
<?php
//db query to obtain i_id - to insert to RESULT table
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_assoc($query_i);
$ins_id = $data_i['i_id'];
//$j = 1;
$arr_ind = 1;
$atext = array(1);
$ans = array(1);
//FOR LOOP TO RETRIEVE VALUES FROM TEXT AREA
for($i=1;$i<=$q_no;$i++){
for($k=1;$k<=$ansspc;$k++){
$repStr = str_replace("1", $k, "answer_1");
echo "Question ". $i .": Answer: ". $repStr;
$ans[] = $_POST[$repStr];
echo $ans;
}
$sql_check = "SELECT a_text FROM answer WHERE q_id='$i'";
$query_ch = mysql_query($sql_check) or die("MySQL Error: " . mysql_error());
$data_ch = mysql_fetch_assoc($query_ch);
$atext[] = $data_ch['q_ans'];
//$j++;
}
...
It was working previously when I had the questions set with one text area each. What I intend to do is have each answer to be compared with each answer suggestion.
Example:
State two advantages of...
Two text area: ans1, ans2
Four suggested answers: soln1, soln2, soln3, soln4
So I'd compare ans1 with soln1, soln2, soln3, soln4 then the same goes for the ans2.
Edited:
//start loop for questions & answers
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
//process returned data
foreach ($_POST['answer'] as $questionNumber => $answerList){
echo "question " . $questionNumber . ": \n";
foreach ($answerList as $key => $answer){
$ans[] = $answer;
echo "answer " . $key . ": " . $answer . "\n";
}//end foreach_in
}//end foreach_out
$jawapan = explode(" ", $ans[$arr_ind]);
$jwpn = trim($jwpn);
foreach($jwpn as $eval){
if (stripos($atext[$arr_ind], $eval) !== false){ //$atext: query for answer suggestions
//answer match with first suggestion
echo "<p align='justify'><img src='image/mark.png' border='0' width='20' height='20'> ". $ans[$arr_ind]. "</p>";
}//if
{else
//answer doesn't match with first suggestion; check next suggestion
for($m=1;$m<=$box;$m++){...}// $box = no. of text area in form
}//else
echo "<p align='justify'><label><b>SUGGESTED ANSWER:</b> <br><input name='answer_".$rad."' type='hidden' value=''>". $atext[$arr_ind] . "</label></p>";
$arr_ind++;
}//foreach
Best is to use arrays in the naming of the textareas
Outputting the textarea (i left out all markup extras just to make it clear)
while ($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)) {
$qfield = $data_q['q_field'];
$qno = $data_q['q_no'];
for ($rad = 1; $rad <= $qfield; $rad++) {
echo "<textarea name='answer[" . $qno . "][" . $rad . "]' id='textarea_" . $qno . "_" . $rad . "'>";
}
}
and processing the returned data
foreach ($_POST['answer'] as $questionNumber => $answerList) {
echo "question " . $questionNumber . ": \n";
foreach ($answerList as $key => $answer) {
echo "answer " . $key . ": " . $answer . "\n";
}
}
Related
I'm working with our project and I noticed that whenever I refresh my page the mysql query repeats itself. When I click a submit button It will go to same page and it will perform the query. Even though i used isset() method to the submitting button, still the query repeats when I refresh/reload the page. Thank you :) !
<html>
<body>
<head>
<link rel="stylesheet" type="text/css" href="Homepagestyle.css">
</head>
<form method = "POST" action = "Forum.php">
<?php
session_start();
mysql_connect("127.0.0.1", "root", "toor");
mysql_select_db("matutorials");
echo "Welcome " . "<a href = 'UserProf.php'>". $_SESSION['username'] . "</a> <br>";
if (isset($_POST['btnProg'])){
echo $_SESSION['prog'] . "<br>";
} else if (isset($_POST['btnNet'])){
echo $_SESSION['net'] . "<br>";
}
?>
<center><font face = 'verdana'><textarea cols = 70 rows = 6 name = 'txtpost'></textarea></font></center><br>
<center><input type = 'submit' name = 'btnPost'></center><br> <br>
<center><table>
<?php
if (isset($_POST['btnProg'])){
$_SESSION['pasamoto'] = 1;
$capRows = "SELECT * FROM page_post WHERE category_id = 1 ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
?>
</table> </center>
<?php
session_start();
if(isset($_POST['btnPost'])){
$post_content = $_POST['txtpost'];
$dttime = date("Y-m-d") . " " . date("h:i:sa");
$var = $_SESSION['pasamoto'];
if ($var == 1){
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
//}
if ($var == 2){
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
//}
?>
</form>
</body>
</html>
If you refresh a page after submitting you form, the POST will still be recognised by some browsers and will cause a second POST to the code. You should update your code to trigger the SQL query on a separate page or function, and then redirect the user to the success / thanks page, where refreshing won't duplicate the query.
Alternatively, you can have a hidden field on your page which contains a unique token and compare it with a cookie. On page load, you save the token to a cookie and to the hidden field on the form. When you submit the form, validate that the token in the hidden form field matches the cookie, then delete the cookie. Refreshing the page after submission will cause the token validation to fail, preventing a duplicate SQL insert.
Just wash out the form data by redirecting the page after insert query
like header('location:home.php')
As #PeeHaa suggested in the comments above use Post-Redirect-Get concept.
Modified your code a bit. Try below:
Forum.php
<head>
<link rel="stylesheet" type="text/css" href="Homepagestyle.css">
</head>
<body>
<form method="POST" action="Forum.php">
<?php
session_start();
mysql_connect("127.0.0.1", "root", "toor");
mysql_select_db("matutorials");
echo "Welcome " . "<a href = 'UserProf.php'>". $_SESSION['username'] . "</a> <br>";
if (isset($_GET['show']))
{
echo $_SESSION['prog'] . "<br>";
}
else if (isset($_GET['show']))
{
echo $_SESSION['net'] . "<br>";
}
?>
<center><font face = 'verdana'><textarea cols = 70 rows = 6 name = 'txtpost'></textarea></font></center><br>
<center><input type = 'submit' name = 'btnPost'></center><br> <br>
<center><table>
<?php
if (isset($_GET['show']))
{
$_SESSION['pasamoto'] = 1;
$capRows = "SELECT * FROM page_post WHERE category_id = 1 ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
?>
</table> </center>
<?php
if(isset($_POST['btnPost']))
{
$post_content = $_POST['txtpost'];
$dttime = date("Y-m-d") . " " . date("h:i:sa");
$var = $_SESSION['pasamoto'];
if ($var == 1)
{
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
if ($var == 2)
{
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
}
header("Location:Forum.php?show=true"); // <==== Note this
?>
</form>
</body>
</html>
Explanation:
The above code will follow the Post-Redirect-Get pattern. The form will post the data to the same page and whatever task you want to perform after form post should be enclosed in,
if(isset($_POST['btnPost']))
{
...
}
and then redirect the user to the same page using,
header("Location:Forum.php?show=true");
the header function will redirect the user to the same page and the GET parameter show will decide what to show after the redirection. The content to show after redirection (or any other time) should be enclosed in,
if(isset($_GET['show']))
{
...
}
I am developing a page for multiple choice questions. User is only able to select an answer for each question. I can't seem to retrieve the value (1 indicates correct answer) of the radio buttons.
Here is structure of two tables that I use
CREATE TABLE IF NOT EXISTS `question` (
`q_id` int(10) NOT NULL AUTO_INCREMENT,
`q_qstn_no` int(11) NOT NULL,
`q_text` varchar(300) NOT NULL,
`q_chpt` int(11) NOT NULL,
PRIMARY KEY (`q_id`)
)
CREATE TABLE IF NOT EXISTS `answer` (
`a_id` int(6) NOT NULL AUTO_INCREMENT,
`q_id` int(10) NOT NULL,
`a_text` varchar(255) NOT NULL,
`a_value` tinyint(1) NOT NULL,
PRIMARY KEY (`a_id`)
)
HTML form containing the radio group.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
session_start();
if(isset($_SESSION['tf1_sid']))
{
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="ques_page_calc1.php">
<p>Questions</p>
<table width="900" border="0" cellpadding="4">
<?php
// db connect
include("dbconn.php");
// db query for questions
$sql_q = "SELECT q_id, q_qstn_no, q_text FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions
$rad2 = 0;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
// echo "<pre>";
// print_r($data_q);
// echo "</pre>";
//
echo "<tr><td width='25' align='center' valign='top'><label><input name='q_no' size='1' type='hidden' value=". $data_q['q_qstn_no'] .">". $data_q['q_qstn_no'] ."</label></td>";
echo "<td>". $data_q['q_text'] ."<br />";
// db query for answers
$sql_a = "SELECT a_id, a_text, a_value FROM answer WHERE q_id=".$data_q['q_id'];
$query_a = mysql_query($sql_a) or die("MySQL Error: " . mysql_error());
//$rad = 0;
// start loop for answers
while($data_a = mysql_fetch_array($query_a, MYSQL_ASSOC)){
echo "<br /><table width='750' border='0'>";
echo "<tr><td><label><input name='answer_".$rad2."' type='radio' value=". $data_a['a_value'] .">". $data_a['a_text'] . "</label></td></tr>";
echo "</table>";
//$rad++;
}
echo "</tr>";
$rad2++;
}
echo "<tr><td><input name='Submit' type='submit' onClick='ques_page_calc1.php' value='Submit'></td></tr>";
mysql_free_result($query_q);
mysql_free_result($query_a);
include("dbconn.php");
?>
</table>
</form>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
?>
The PHP file to get the value selected
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
// include db connection file
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
echo $id;
$correct = 0;
$ev_id = 1;
//db query to obtain i_id
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_array($query_i, MYSQL_ASSOC);
print_r($data_i);
// capture values from HTML form
if(!empty($_POST['answer_'.$rad2]))
{
foreach(($_POST['answer_'.$rad2]) as $ans)
{
echo $ans;
var_dump($_POST);
if($ans == 1)
$correct = $correct + 1;
}
//echo $correct;
// insert answer to table
//$sql_eval = "INSERT INTO eval_set (ev_id, q_id, response, created) VALUES ('" . $ev_id . "', '" . $ques_no . "', '" . $ans . "', CURDATE())";
//mysql_query($sql_eval) or die ("Error: " . mysql_error());
//}
}
//
// insert result to table
//$sql_result = "INSERT INTO result (r_score, ev_id, s_id, i_id) VALUES ('" . $correct . "', '" . $ev_id . "', '" . $id . "', '" . $data_i . "')";
//mysql_query($sql_result) or die ("Error: " . mysql_error());
//echo "Result: " . $correct . " questions correct.";
//header("Location:ass_result.php");
}
// close db connection
mysql_close($dbconn);
?>
I thought it was the $_POST['answer_'.$rad2] that was causing the problem since I wasn't sure how to concatenate variables to name field. But now that's changed, there is still no output beyond print_r($data_i); line in the PHP file.
You don't need to give your radio group buttons different names. All of your choices will have a single name (say 'answer') and your PHP script will simply check for
$_POST['answer']
this will give you the selected radio button's value. So however many radio buttons you have for a certain question, give all of them the same name and you're fine. This will also make sure that only one of the radio buttons related to each other can be checked.
I solved it :) I took away the if(!empty...) and replaced it with these.
for($i=1;$i<=$qno;$i++){
$repStr = str_replace("1", $i, "answer_1");
//echo "Question ". $i .": ". $repStr;
$ans = $_POST[$repStr];
//echo "". $radio ."<br>";
if($ans == 1)
$correct = $correct + 1;
// everything before is FIXED :D
// insert answer to table
$sql_eval = "INSERT INTO eval_set (ev_id, q_id, response, created) VALUES ('MAX(ev_id)+1 ', '" . $i . "', '" . $ans . "', CURDATE())";
mysql_query($sql_eval) or die ("Error: " . mysql_error());
}
i will use my old posted codes, coz i am working on the same program. what i want is how could i make it possible to save all selected values in one row which the studentid of a user will not be repeated. pls help...
<?php session_start(); ?>
<?php
//server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'user';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
echo 'Student ID: '. $voter.'';
echo "<br />";
if ($_POST['representatives']){
$check = $_POST['representatives'];
foreach ($check as $ch){
global $voter;
$mysqli->query("INSERT INTO sample (studentid, candidate1) VALUES ('".$voter."', '". $ch ."')");
echo $ch. "<br>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<script type="text/javascript">
<!--
function get_representatives_value()
{
for (var i=0; i < document.list.representatives.length; i++)
{
if (document.list.representatives[i].checked)
{
return document.getElementById('candidates').innerHTML = document.list.representatives[i].value
}
}
}
//-->
</script>
title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="candidate.css" rel="stylesheet" type="text/css">
</head>
<body> <p id="txt"></p>
<form name="list" action="president2.php" method="post" onSubmit="return get_representatives_value()">
<div id="form">
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM candidate_info WHERE position= 'representatives' AND department ='CCEITE' ORDER BY cand_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>Student ID</th><th>Candidate ID</td><th>Course</th><th colspan = '3'>Name</th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->cand_studid . "</td>";
echo "<td>".$row->cand_id."</td>";
echo "<td>" . $row->course . "</td>";
echo "<td coslpan ='5'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td><input type ='checkbox' name='representatives[]' id='". $row->cand_studid ."' value='" . $row->cand_studid . "' onchange='get_representatives_value()' /></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
echo "<input type='submit' name='representatives value='Submit' />";
?>
</div>
</form>
<table>
<tr><td>Preview List</td></tr>
<tr><td>Candidates: </td><td id="candidates"> </td></tr>
</table>
</body>
</html>
this the preview of my output and selected checkbox
now this is the preview of my database. this one is the result of my selection from the above preview which the student ID is repeated on my table.
what i want is to save like this
and one more thing, how could i make a preview of all i selected on the checkboxes, here is my preview output, below the table is the preview list of candidates as the user click on the checkbox. but it returns only one and only the last selected value as selecting multiple checkboxes will be printed. how could i apply this method in an array coz this preview, i remove the '[]' on my input type name='representative' and it works, but not in the presence of '[]'.
I don't know if I read your questions correctly, but...
For your Insert Issue
I don't know if the way you're storing the data in the database is the best method, but if you want to use what you have, you can just insert your record like this (assuming you've put in some validation script to prevent users from selecting more than 2 candidates):
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
if ($_POST['representatives']){
$check = $_POST['representatives'];
$mysqli->query("INSERT INTO sample (studentid, candidate1, candidate2) VALUES ('". $voter ."', '". $check[0] ."', '". $check[1] ."')");
}
}
?>
For your Preivew Issue:
I'm assuming you wanted something like this for your preview to show the studentid with the choices for candidate1 and candidate2:
<h3>Preview List</h3>
<table>
<tr><th>StudentID</th><th>Candidate 1</th><th>Candidate 2</th></tr>
<?php
$result = $mysqli->query("SELECT * FROM candidate_info");
while ($row = $result->fetch_object())
{
echo "<tr><td>" . $row->studentid . "</td><td>" . $row->candidate1 . "</td><td>" . $row->candidate2 . "</td></tr>";
}
$mysqli->close();
?>
</table>
Here is some pseudo code you can use to update the sample table:
$candidate=array(null,null);
$candidateCounter=0;
foreach ($check as $ch){
$candidate[$candidateCounter]=$ch;
$candidateCounter++;
if(candidateCounter>1){
something wrong, only 2 candidates can be selected
}
}
UPDATE sample set $candidate1=candidate[0], $candidate2=candidate[1] WHERE
studentid=$voter
I have three php scripts. main.php questions.php and values.php
Here's the code
main.php
<html>
<head>
<title></title>
</head>
<body>
<h1>Be Prepare for the battle</h1>
<?php
$strTitle = "Begin";
$strLink = "<a href = 'question.php?ques_id=1'>" . $strTitle ."</a>";
echo $strLink;
?>
</body>
</html>
questions.php
<?php
require_once('../connect.php');
$quesSQL = mysql_query("SELECT * FROM `questions` WHERE `ques_id`=". $_GET["ques_id"]);
if(!mysql_num_rows($quesSQL) >= 1)
{
die('Complete.');
}
$next = $_GET["ques_id"];
while($row = mysql_fetch_array($quesSQL)) {
$id = $row['ques_id'];
$strTitle = $row['ques_title'];
echo "<li>" . $strTitle . "</li><br/>";
}
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE " . $id . "= ques_id");
echo "<form action=\"values.php\" method=\"POST\">";
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo "<input type =\"radio\" name =\"valueIn\" value=" . $strValues . " />" . $strOptions . "<br/>";
}
echo "</form>";
$strTitle = "<input type =\"submit\" value=\"Next\">";
$next = $next + 1;
$strLink = "<a href = 'values.php?ques_id=" . $next . "'>" . $strTitle ."</a>";
echo $strLink;
mysql_close();
?>
values.php
<?php
require_once('../connect.php');
$input = $_POST['valueIn'];
$ansSQL = mysql_query("SELECT `answer` FROM questions WHERE 1-".$_GET["ques_id"]."= ques_id");
$marks = 0;
if($input == $ansSQL)
{
$marks = $marks+1;
}
else
{
$marks = $marks+0;
}
echo $marks;
?>
Now problem is i have to pass one value from second script(questions.php) to third script(values.php).
And it is from the <form> section in radio button's name value "valueIn". But I can't do that. Because I'm sending another value ques_id with $strLink variable at the end of the second script.
So how can i do that?
I'm not sure why your using a link to handle what should probably be in the form. As stated by anusha you should be using a hidden input field for ques_id like so
questions.php
<?php
require_once('../connect.php');
$quesSQL = mysql_query("SELECT * FROM `questions` WHERE `ques_id`=". $_GET["ques_id"]);
if(!mysql_num_rows($quesSQL) >= 1)
{
die('Complete.');
}
$next = $_GET["ques_id"];
while($row = mysql_fetch_array($quesSQL)) {
$id = $row['ques_id'];
$strTitle = $row['ques_title'];
echo "<li>" . $strTitle . "</li><br/>";
}
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE " . $id . "= ques_id");
echo "<form action=\"values.php\" method=\"POST\">";
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo "<input type =\"radio\" name =\"valueIn\" value=" . $strValues . " />" . $strOptions . "<br/>";
}
$next = $next + 1;
$strLink = '<input type="hidden" name="ques_id" value="'.$next.'">';
echo $strLink;
$strTitle = "<input type =\"submit\" value=\"Next\">";
echo $strTitle;
echo "</form>";
mysql_close();
?>
Both variables when then be available via $_POST on the next step like below
$input = $_POST['valueIn'];
$ques_id = $_POST['ques_id'];
You can use hidden input like Mike's answer, or you can still use GET parameter like this:
questions.php
<?php
// .........
// .........
// .........
// .........
// add / change your code for this part
$next = (int) $next;
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE ques_id = " . $next);
echo '<form action="values.php?ques_id=' . ($next+1) . '" method="POST">';
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo '<input type="radio" name ="valueIn" value="' . $strValues . '" />' . $strOptions . '<br/>';
}
echo '<input type="submit" value="Next">';
echo "</form>";
mysql_close();
// end change
?>
values.php
<?php
// add / change your code for this part
$_GET["ques_id"] = (int) $_GET["ques_id"];
$ansSQL = mysql_query("SELECT `answer` FROM questions WHERE ques_id = " . ($_GET["ques_id"]-1));
// end change
// .........
// .........
// .........
// .........
You can add multiple parameters with 'a' tag.
Like
"<a href = 'values.php?ques_id=".$next." & ques_id1=1'>" . $strTitle ."</a>"
You can also use a hidden input field for variable $question_id and submit the form
i try to make checkboxes. When i click checkbox it makes isPremium = 1 if i click a checked checkbox it makes isPremium = 0
However: when i click a checked checkbox it does not work..
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
$dbResult = mysql_query("select * from profiles");
while ($info = mysql_fetch_array($dbResult)) {
if ($info['isPremium'] == 0)
echo "<input type=checkbox name='check2[]' id='check2' value=" . $info['id'] . ">";
else
echo "<input type=checkbox name='check1[]' id='check1' value=" . $info['id'] . " checked>";
echo $info['profileName'] . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
if (isset($_POST['check2'])) {
$arrPremium = $_POST['check2'];
foreach ($arrPremium as $result) {
mysql_query("UPDATE profiles set isPremium=1 where id=" . $result . "");
}
}
else
{
$arrPremium = $_POST['check1'];
foreach ($arrPremium as $result2) {
mysql_query("UPDATE profiles set isPremium=0 where id=" . $result2 . "");
}
}
}
?>
when i click a checked checkbox it makes another checkbox unclick.
This is the checkbox page
I have refactored your code into this:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$update = (isset($_POST['check']) && is_array($_POST['check']));
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
while ($info = mysql_fetch_array($dbResult))
{
if ($update)
{
$info['isPremium'] = (in_array($info['id'], $_POST['check']) ? 1 : 0);
mysql_query("UPDATE profiles SET isPremium = " . $info['isPremium'] . " WHERE id = " . $info['id']);
}
echo "<input type=checkbox name='check[]' value=" . $info['id'] . ($info['isPremium'] == 0 ? "" : "checked") . " />";
echo htmlspecialchars($info['profileName']) . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
?>
There were several problems with your original code:
Several HTML input elements with the same ID. This is wrong. We can have several elements with the same name attribute, but the id attribute should be unique for each element.
The database UPDATE code runs after displaying the form. This is wrong. In this case, we should update the database prior to generating the HTML output.
IMPORTANT: There is no need of two different POST arrays (check1 and check2). We only need one array. The checked boxes will be posted by the browser. The unchecked boxes will not be posted by the browser. As the id is the value, we can use the in_array function to verify if the checkbox for an item was checked or not.
It is a good idea to escape things you will output as HTML from the database. Otherwise, the application is vulnerable for some kinds of attack. The function htmlspecialchars is useful for this purpose.
If I understand correctly what you're trying to achieve, your code is needlessly complicated. You should use isset to check whether the value of a checkbox was included in the $_POST array. If yes, the checkbox was checked.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
echo "<form action='#' method='post'>";
$dbResult = mysql_query("SELECT * FROM profiles");
$profileid = array();
while ($info = mysql_fetch_array($dbResult)) {
echo "<input type=\"checkbox\" name=\"" . $info['id'] . "\" " . ($info['isPremium'] != 0 ? "checked " : "") . "/>";
echo $info['profileName'] . "<br />";
$profileid[] = $info['id'];
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
foreach ($profileid as $id) {
if (isset($_POST[$id])) {
mysql_query("UPDATE profiles SET isPremium=1 WHERE id=" . $id);
} else {
mysql_query("UPDATE profiles SET isPremium=0 WHERE id=" . $id);
}
}
}
?>
Checkboxes typically send the value "on" to the server, regardless of what value attribute is set. If you can, try to use radio buttons instead, as these send the proper value to the server. If that's not an option, have the name of the checkbox be check1[".$info['id']." and access array_keys($_POST['check1']).