Doesn't POST next questions of the subject - php

<?php
$singleSQL = mysql_query("SELECT * FROM questions WHERE subject_id='$subject' AND question_id='$question'");
$row = mysql_fetch_array($singleSQL);
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysql_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="checkbox" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()">Atsakyti</button></span>';
echo $output;
?>
Doesn't POST questions on selected subject. The do not find the question in database, because questions have different subject ID and it's not in any order.
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid=" + id + "&radio=" + x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if (p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var response = hr.responseText.split("|");
if (response[0] == "finished") {
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("post", "questions.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send("subject=<?php echo $subject; ?>&question=<?php echo $next; ?>");
}
}
p.send(vars);
}
this is the function that button triggers

check your query. $question_id missing.
$sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question_id' ORDER BY rand()");

Related

Get category_id from url and send it to php via ajax

I have a page filter.php?category_id=1. It comes from a index.php <a href="filter.php?category_id=<?php echo $category_id; ?>"> I try to send category_id to file fetch_data.php.
filter.php
$(document).ready(function(){
filter_data(1);
function filter_data(page)
{
//$("#preloader").show();
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var filter_category = get_filter('filter_category');
var filter_material = get_filter('filter_material');
var filter_source_light = get_filter('filter_source_light');
var filter_dimming_options = get_filter('filter_dimming_options');
var filter_color_temperature = get_filter('filter_color_temperature');
var filter_degree_tightness = get_filter('filter_degree_tightness');
$.ajax({
//url:"fetch_data.php",
url:'fetch_data.php?category_id=<?php echo $_GET['category_id']; ?>',
method:"POST",
data:{action:action, filter_category:filter_category, filter_material:filter_material, filter_source_light:filter_source_light, filter_dimming_options:filter_dimming_options, filter_color_temperature:filter_color_temperature, filter_degree_tightness:filter_degree_tightness, page:page},
success:function(data){
$('.filter_data').html(data);
}
});
}
fetch_data.php
//$category_id = "1";
$category_id = $_GET['$category_id'] ?? '';
if(isset($_POST["action"])) {
$sql1 = "SELECT * ";
$sql1 .= "FROM photographs ";
$sql1 .= "WHERE category_id='" . $database->escape_string($category_id) . "' ";
I don't know what I'm doing wrong. When I set $category_id = "1"; or "2" everything works
Solution:
filetr.php
$(document).ready(function(){
filter_data(1);
function filter_data(page)
{
//$("#preloader").show();
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var filter_category = get_filter('filter_category');
var filter_material = get_filter('filter_material');
var filter_source_light = get_filter('filter_source_light');
var filter_dimming_options = get_filter('filter_dimming_options');
var filter_color_temperature = get_filter('filter_color_temperature');
var filter_degree_tightness = get_filter('filter_degree_tightness');
var category_id = "<?php echo $_GET['category_id']; ?> ";
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, filter_category:filter_category, filter_material:filter_material, filter_source_light:filter_source_light, filter_dimming_options:filter_dimming_options, filter_color_temperature:filter_color_temperature, filter_degree_tightness:filter_degree_tightness, page:page, category_id:category_id},
success:function(data){
$('.filter_data').html(data);
}
});
}
fetch_data.php
$category_id = $_POST['category_id'] ?? '';
if(isset($_POST["action"])) {
$sql1 = "SELECT * ";
$sql1 .= "FROM photographs ";
$sql1 .= "WHERE category_id='" . $database->escape_string($category_id) . "' ";

PHP POST form after AJAX call

Problem: My php form does not submit.
This is my page:
It has a php rendered list of colors:
<div class="table-container">
<div>
<table class="myTable" id="myTable">
<tr class="header">
<th>Variants</th>
<th>Size</th>
<th>Price (€)</th>
</tr>
<?php
$current_name = $_GET['prod-name'];
$get_product_det = "SELECT * FROM product_details WHERE product_name='$current_name' ORDER BY position";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$id = $row_product_det['id'];
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
$position = $row_product_det['position'];
echo "<tr data-index='$id' data-position='$position'>
<td><a id='$id'>$product_variant</a></td>
<td>$product_size</td>
<td>$product_price</td>
</tr>";
};
?>
</table>
</div>
Each color has a unique ID. Clicking on a color fires the AJAX script that works fine:
<div class='product-det-div' id='product_details'>
<script>
var links = document.getElementsByTagName('a');
for (var i = 0, il = links.length; i < il; i++) {
links[i].onclick = function() {
var id = this.id;
var product_details = document.getElementById('product_details');
var request = new XMLHttpRequest();
request.open('POST', 'product_details.php?variant_id=' + id, true);
request.onreadystatechange = function() {
if (request.readyState === 4 & request.status === 200) {
product_details.innerHTML = request.responseText;
} else {
product_details.innerHTML = 'An error occurred during your request: ' + request.status + ' ' + request.statusText;
}
};
request.send();
};
};
</script>
</div>
When the ajax call happens, what happens to the URL of the page? I'm passing the ID of the color through the URL but when trying to GET it with PHP it seems it doesn't find it.
Here's the code of the page:
$current_id = $_REQUEST['variant_id'];
$get_product_det = "SELECT * FROM product_details WHERE id=$current_id";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
echo "
<form action='' method='post'>
<h2 style='margin-bottom: 20px;'>$product_variant</h2>
<div><label>Nome Prodotto</label><input value='$product_variant'></div>
<div><label>Dimensione</label><input value='$product_size' type='number' name='product_size'></div>
<div><label>Prezzo (€)</label><input value='$product_price' id='product_price' name='product_price'></div>
<button type='submit' name='edit_variant_btn'>Send</button>
</form>
";
if(isset($_POST['edit_variant_btn'])) {
$variant = $_POST['product_size'];
$current_id = $_REQUEST['variant_id'];
$update_size = "UPDATE product_details SET size = '$variant' WHERE id = '$current_id'";
$run_update = mysqli_query($con, $update_size);
if($run_update) {
echo "<script>window.open('variable_product.php?prod-name=Polycolor', '_self');</script>";
}
}
};
?>
Thank you for your time, any help appreciated.
EDIT: I tried all the changes you all adviced, also tried $_REQUEST["variant_id"] as Banujan Balendrakumar said, but still no result.
The only way I found to make it work was to change the form action from this:
<form action='' method='post'>
to
<form action='product_details.php?variant_id=$current_id' method='post'>
This way it works because on button click, it opens that page and gets the ID value from there but it's just a way to get around the problem...
Any other ideas?
It's working for me....
<div class="table-container">
<div>
<table class="myTable" id="myTable">
<tr class="header">
<th>Variants</th>
<th>Size</th>
<th>Price (€)</th>
</tr>
<?php
$con = new mysqli('localhost','root','','check');
$get_product_det = "SELECT * FROM product_details ORDER BY position";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$id = $row_product_det['id'];
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
$position = $row_product_det['position'];
echo "<tr data-index='$id' data-position='$position'>
<td><a id='$id'>$product_variant</a></td>
<td>$product_size</td>
<td>$product_price</td>
</tr>";
};
?>
</table>
</div>
<div class='product-det-div' id='product_details'>
<script>
var links = document.getElementsByTagName('a');
for (var i = 0, il = links.length; i < il; i++) {
links[i].onclick = function() {
var id = this.id;
var product_details = document.getElementById('product_details');
var request = new XMLHttpRequest();
request.open('POST', 'product_details.php?variant_id=' + id, true);
request.onreadystatechange = function() {
if (request.readyState === 4 & request.status === 200) {
product_details.innerHTML = request.responseText;
} else {
product_details.innerHTML = 'An error occurred during your request: ' + request.status + ' ' + request.statusText;
}
};
request.send();
};
};
</script>
</div>
product details
<?php
$current_id = $_REQUEST['variant_id'];
$con = new mysqli('localhost','root','','check');
$get_product_det = "SELECT * FROM product_details WHERE id=$current_id";
$run_product_det = mysqli_query($con, $get_product_det);
while ($row_product_det = mysqli_fetch_array($run_product_det)){
$product_variant = $row_product_det['product_variant'];
$product_size = $row_product_det['size'];
$product_price = $row_product_det['price'];
echo "
<form action='' method='post'>
<h2 style='margin-bottom: 20px;'>$product_variant</h2>
<div><label>Nome Prodotto</label><input value='$product_variant'></div>
<div><label>Dimensione</label><input value='$product_size' type='number' name='product_size'></div>
<div><label>Prezzo (€)</label><input value='$product_price' id='product_price' name='product_price'></div>
<button type='submit' name='edit_variant_btn'>Send</button>
</form>
";
if(isset($_POST['edit_variant_btn'])) {
$variant = $_POST['product_size'];
$current_id = $_REQUEST['variant_id'];
$update_size = "UPDATE product_details SET size = '$variant' WHERE id = '$current_id'";
$run_update = mysqli_query($con, $update_size);
if($run_update) {
echo "<script>window.open('variable_product.php?prod-name=Polycolor', '_self');</script>";
}
}
};
?>

When I press the post button my comment doesn't post to my database

So the issue i'm having is that when I click the post button nothing happens and a comment doesn't display or go to my database. I have checked for spelling mistakes and believe I have got them all.
This is my HTML form called community.php
<div class="page-container">
<?php
get_total();
require_once 'check_com.php';
?>
<form action="" method="post" class="main">
<label>Enter a Brief Comment</label>
<textarea class="form-text" name="comment" id="comment"></textarea>
<br />
<input type="submit" class="form-submit" name="new_comment" value="Post">
</form>
<?php get_comments(); ?>
</div>
This is my js script called global.js
$(document). ready(function() {
$(".child-comments").hide();
$("a#children").click(function() {
var section = $(this).attr("name");
$("#C-" + section).toggle();
});
$(".form-submit").click(function() {
var commentBox= $("#comment");
var commentCheck= commentBox.val();
if(commentCheck == '' || commentCheck == NULL) {
commentBox.addClass("form-text-error");
return false;
}
});
$(".form-reply").click(function() {
var replyBox= $("#new-reply);
var replyCheck= replyBox.val();
if(replyCheck == '' || replyCheck == NULL) {
replyBox.addClass("form-text-error");
return false;
}
});
$("a#reply").one("click", function() {
var comCode = $(this).attr("name");
var parent = $(this).parent();
parent.append("<br / ><form actions='' method='post'><textarea class='form-text' name='new-reply' id='new-reply' required='required'></textarea><input type='hidden' name='code' value='"+comCode"' /><input type='submit' class='form-submit' id='form-reply' name='new_reply' value='Reply'/></form>")
});
})
Check_com.php file
<?php
// new comment fucntion
if(isset($_POST['new_comment'])) {
$new_com_name = $_SESSION['user'];
$new_com_text = $_POST['comment'];
$new_com_date = date('Y-m-d H:i:s');
$new_com_code = generateRandomString();
if(isset($new_com_text)) {
mysqli_query($conn, "INSERT INTO `parents` (`user`, `text`, `date`, `code`) VALUES ('$new_com_name', '$new_com_text', '$new_com_date', '$new_com_code')");
}
header ("Location: ");
}
// new reply
if(isset($_POST['new_reply'])) {
$new_reply_name = $_SESSION['user'];
$new_reply_text = $_POST['new-reply'];
$new_reply_date = date('Y-m-d H:i:s');
$new_reply_code = $_POST('code');
if(isset($new_reply_text)) {
mysqli_query($conn, "INSERT INTO `children` (`user`, `text`, `date`, `par_code`) VALUES ('$new_reply_name', '$new_reply_text', '$new_reply_date', '$new_reply_code')");
}
header ("Location: ");
}
?>
Functions.php File
<?php
session_start();
$_SESSION['user'] = 'Admin';
function get_total() {
require 'includes/dbh.inc.php';
$result = mysqli_query($conn, "SELECT * FROM `parents` ORDER BY `date` DESC");
$row_cnt = mysqli_num_rows($result);
echo '<h1>All Comments ('.$row_cnt.')</h1';
}
function get_comments() {
require 'includes/dbh.inc.php';
$result = mysqli_query($conn, "SELECT * FROM `parents` ORDER BY `date` DESC");
$row_cnt = mysqli_num_rows($result);
foreach($result as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$user = $item['user'];
$comment = $item['text'];
$par_code = $item['code'];
echo '<div class="comment" id="'.$par_code.'">'
.'<p class="user">'.$user.'</p> '
.'<p class="time">'.$date.'</p>'
.'<p class="comment-text">'.$comment.'</p>'
.'<a class="link-reply" id="reply" name="'.$par_code.'">Reply</a>';
$chi_result = mysqli_query($conn, "SELECT * FROM `children` WHERE `par_code`='$par_code' ORDER BY `date` DESC");
$chi_cnt = mysqli_num_rows($chi_result);
if($chi_cnt == 0){
}else {
echo '<a class="link-reply" id="children" name="'.$par_code.'"><span id="tog_text">replies</span> ('.$chi_cnt.')</a>'
.'<div class="child-comments" id="C-'.$par_code.'">';
foreach ($chi_result as $com) {
$chi_date = new dateTime($com['date']);
$chi_date = date_format($chi_date, 'M j, Y | H:i:s');
$chi_user = $com['user'];
$chi_com = $com['text'];
$chi_par = $com['par_code'];
echo '<div class="child" id="'.$par_code.'-C">'
.'<p class="user">'.$chi_user.'</p> '
.'<p class="time">'.$chi_date.'</p>'
.'<p class="comment-text">'.$chi_com.'</p>'
.'</div>';
}
echo '</div>';
}
echo '</div>';
}
}
function generateRandomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characterLength = strlen($characters);
$randomString = '';
for($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $characterLenght - 1)];
}
return $randomString;
}
?>
Either remove action="" or change it to action="community.php"

validating a drop down list using javascript

<?PHP
session_start();
if (isset($_SESSION['login']) && $_SESSION['login'] = '1') {
//=========================================================
//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();
$D = array();
$E = array();
$quesType = array();
$survey_Answers1 = '';
$nominatefriend = '';
//============================================
// OPEN A CONNECTION TO THE DATABASE
//============================================
$user_name = "root";
$password = "";
$database = "surveyTest";
$server = "127.0.0.1";
$mysqli = new mysqli($server, $user_name, $password, $database);
$SID = $_SESSION['user'];
if (!mysqli_connect_errno()) {
$result = $mysqli->query("SELECT * FROM tblquestions ORDER BY SUBSTRING(QID,2)+0");
$numRows = mysqli_num_rows($result); //return number of rows in the table
//var_dump($numRows);
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="survey.php">';
for ($i = 1; $i <= $numRows; $i++)
{
//var_dump ($mysqli->error);
//var_dump($i);
$db_field = mysqli_fetch_assoc($result);
//var_dump($db_field);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$quesType = $db_field['qType'];
//var_dump($quesType);
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
$D[$i] = $db_field['qD'];
$E[$i] = $db_field['qE'];
if ($quesType == 'rating')
{
echo '<P>';
print $qNum.': '.$question[$i];
echo '<P>';
if ($A[$i] != ""){
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= '".$A[$i]."' id = '".$qNum."'>";
print $A[$i];
}
echo '<P>';
if ($B[$i] != ""){
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= '".$B[$i]."' id = '".$qNum."'>";
print $B[$i];
}
echo '<P>';
if ($C[$i] != ""){
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= '".$C[$i]."' id = '".$qNum."'>";
print $C[$i];
}
echo '<P>';
if ($D[$i] != ""){
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= '".$D[$i]."' id = '".$qNum."'>";
print $D[$i];
}
echo '<P>';
if ($E[$i] != ""){
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= '".$E[$i]."' id = '".$qNum."'>";
print $E[$i];
}
echo "<span style='color:red' id='radio_error'></span>";
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;
}
else if ($quesType == 'nominate')
{
//echo "<INPUT TYPE = 'hidden' Name = '".$qNum."' id = '".$qNum."'>";
$number_of_Combos = $A[$i];
//var_dump($number_of_Combos);
echo '<p>';
print $qNum.': '.$question[$i];
echo '</BR>';
for ($j = 1; $j <= $number_of_Combos; $j++)
{
$nominatefriend = $qNum.$j;
//var_dump($nominatefriend);
$result_Combo = $mysqli->query("SELECT SID, fName, lName FROM students WHERE SID!='$SID'");
echo "<select name = '".$nominatefriend."' id = '".$qNum."'>";
echo "<option value = '0'>".'Select a Name'."</option>";
while ($select_query_array = mysqli_fetch_array($result_Combo))
{
echo "<option value='".$select_query_array['SID']."'>".$select_query_array['fName'].' '.$select_query_array['lName']."</option>";
}
echo "</select>";
}
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
//var_dump ($qNum);
}
}
echo '<p>';
echo "<INPUT TYPE = 'hidden' Name = 'h2' VALUE = '".$survey_Answers1."'>";
echo '<p>';
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
echo '</form>';
//$value1 = $_POST['nominateFriend1'];
//var_dump($value1);
//$value2 = $_POST['nominateFriend2'];
//var_dump($value2);
//$value3 = $_POST['nominateFriend3'];
//var_dump($value3);
mysqli_close($mysqli);
}
else {
print "Error getting Survey";
mysqli_close($mysqli);
}
}
else
{
header("location:login.php");
}
$_SESSION['user'] = $SID; // refers to student ID from the login page
?>
<html>
<head>
<title>Radio Buttons</title>
</head>
<body>
<!--
<P>
<FORM NAME ="form2" METHOD ="GET" ACTION ="viewResults.php">
<INPUT TYPE = "Submit" Name = "Submit2" VALUE = "View results">
<INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID; ?>>
</FORM>
-->
<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 = '';
var len = <?php echo $numRows; ?>;
$('input[type=Radio]:checked').each(function() {
if (answers !== '') {
answers += ',';
}
answers += $(this).val();
//alert(answers);
})
$('input[name=h2]').val(answers);
for (var i = 1; i <= len; i++ ) {
var qNum = 'q'+i;
//document.write(qNum);
if ($('#'+qNum+'').is(':radio')) {
if (($('input[name='+qNum+']:checked').length == 0) ){
alert("No Selection is made for "+ qNum);
return false;
}
}
else if ($('#'+qNum+'').is('select')) {
var j = 1;
var nominatefriend = qNum+j;
alert (nominatefriend);
var check = '';
var chosen = new Array();
while (check = document.getElementsByName("nominatefriend")) {
alert(check);
var len = document.form1[nominatefriend].length;
alert (len);
for (var i = 0; i < len; i++) {
if (document.form1[nominatefriend[i]].selected) {
chosen[j] = document.form1[nominatefriend[i]].value;
alert (chosen[j]);
}
}
j++;
nominatefriend = qNum+j;
alert (nominatefriend);
}
}
} // for loop
}); // form submit function
}// form.length
})//function
</script>
</body>
</html>
I'm trying to validate the drop down list which is created dynamically based on a value in mysql database. However, I'm getting the following error: TypeError: document.form1.nominatefriend is undefined in the following if condition:
if (document.form1[nominatefriend[i]].selected) {
chosen[j] = document.form1.nominatefriend[i].value;
alert (chosen[j]);
}
$nominatefriend = $qNum.$j;
echo "<select name = '".$nominatefriend."' id = '".$qNum."'>";
so it's just undefined yet
The error says that nominatefriend is undefined.
If I look into your PHP file code I find that in line number 99 and 102 you have as
$nominatefriend = $qNum.$j;
echo "<select name = '".$nominatefriend."' id = '".$qNum."'>";
If I look into more I find $qNum as
$qNum = 'q1';
Thus it will be probably document.form1.q1[i] rather than document.form1.nominatefriend[i].
Error is in the naming, so if you can view source the page, you will probably find the right value that should be used in your js.

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
}

Categories