Fetching data from a MySQL table and inserting into another table - php

I am fetching the data from the MySQL table in a while loop, and inserting the form data into another MySQL table in action page in foreach, but I do not get the correct value of the radio button, I am attaching my code, please help.
<?php
$i = 1;
$j = 1;
while ($row = mysqli_fetch_array($questions)) {
?>
<div class="control-group">
<label class="control-label" for="focusedInput">(<?php echo $i; ?>)
<?php
$questionid = $row['question_id'];
$question = $row['question'];
?>
<input type="hidden" name="questionid[]" value="<?php echo $questionid; ?>" />
<input type="hidden" name="question[]" value="<?php echo $question; ?>" />
<?php echo $row['question']; ?></label>
<div class="controls">
<?php
if ($row['answer_type'] == "Ratings") {
echo "
<p>
Low<input type='radio' name='rating$i' value='1' id='rating_0'>
<input type='radio' name='rating$i' value='2' id='rating_1'>
<input type='radio' name='rating$i' value='3' id='rating_2'>
<input type='radio' name='rating$i' value='4' id='rating_3'>
<input type='radio' name='rating$i' value='5' id='rating_4'>High
</p>
";
$i++;
} else if ($row['answer_type'] == "Comments") {
echo "<textarea name='answer[]' cols='' rows=''></textarea>";
$j++;
}
echo "<br />";
?>
</div>
</div>
<?php } ?>
Action File Code
foreach($_POST['questionid'] as $key=>$questionid){
$questionid = $_POST['questionid'][$key];
$answer = $_POST['answer'][$key];
$result3 = mysqli_query($con, "select question,answer_type from questions where question_id=$questionid;");
while($row = mysqli_fetch_array($result3)) {
$question = $row['question'];
$answer_type = $row['answer_type'];
if($answer_type == "Comments") {
$query2 = "insert into review_details (review_id,survey_id,question_id,question,answer_freeresponse) values(1,$_SESSION[surveyid],$questionid,'$question','$answer')";
$result2 = mysqli_query($con,$query2);
if(!$result2) {
echo mysqli_error($result2);
}
}
else if($answer_type == "Ratings") {
$query2 = "insert into review_details (review_id,survey_id,question_id,question,answer_rating) values(1,$_SESSION[surveyid],$questionid,'$question',$key)";
$result2 = mysqli_query($con,$query2);
if(!$result2) {
echo mysqli_error($result2);
}
}
}
$i++;
}
Output
I want to store the ratings displayed as a radio button, I guess its taking the counter incremented as variable $key, I don't know how to store the values of the radio button.

I guess you will get your radio button value as,
$ratingKey = "rating".$key;
$rating = $_POST[$ratingKey];
Than use $rating in your insert query instead of $key.
INSERT into review_details (review_id,survey_id,question_id,question,answer_rating)
values(1,$_SESSION[surveyid],$questionid,'$question',$rating)

Related

Cant save user input from radio button in php

I have retrieve data from lvl1itquepaper and display it with 4 radio button and save the user input to another table call lvl1itresult but when I press save, no matter which option I choose, the answer that will be saved into database sure is option 4 even if the student select other option.
<?php
include('../dbconnect.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Online Examination System</title>
</head>
<body>
<div id="container">
<h1>Level 1 IT Question Paper</h1>
<h2>Please read the question carefully and answer it confidently. Good Luck All!</h2>
<?php
if(isset($_POST['Submit']))
{
$sql="SELECT * from lvl1itquepaper";
$run_que = mysqli_query($mysqli, $sql);
$check_que = mysqli_num_rows($run_que);
while ($row=$run_que->fetch_assoc())
{
$questionno = $row['questionno'];
$question = $row['question'];
$option1 = $row['option1'];
$option2 = $row['option2'];
$option3 = $row['option3'];
$option4 = $row['option4'];
$ans_array = array($option1, $option2, $option3, $option4);
$student_ans = $row['option1'];
$student_ans = $row['option2'];
$student_ans = $row['option3'];
$student_ans = $row['option4'];
$sql="Insert into lvl1itresult (questionno, question, studentans, username) values ('.$questionno.', '$question', '$student_ans', '".$_SESSION['login_user']."')";
$submit = $mysqli->query($sql);
}
}
?>
<form method= "post">
<?php
echo "Welcome, ";
$sql="SELECT * from lvl1itstudent WHERE username= '".$_SESSION['login_user']."'";
$find_student = mysqli_query($mysqli, $sql);
$check_student = mysqli_num_rows($find_student);
if ($check_student>0){
while($row = $find_student->fetch_assoc())
{
echo $row['username'];
}
}
echo "<br><br><br><br>";
$sql="SELECT * from lvl1itquepaper";
$run_que = mysqli_query($mysqli, $sql);
$check_que = mysqli_num_rows($run_que);
if($check_que>0){
while ($row=$run_que->fetch_assoc())
{
$questionno = $row['questionno'];
$question = $row['question'];
$option1 = $row['option1'];
$option2 = $row['option2'];
$option3 = $row['option3'];
$option4 = $row['option4'];
$ans_array = array($option1, $option2, $option3, $option4);
shuffle($ans_array);
echo "".$questionno. "." .$question."<br>";
echo "<input type='radio' name='.$questionno.' value='".$ans_array[0]."'>".$ans_array[0]."<br>";
echo "<input type='radio' name='.$questionno.' value='".$ans_array[1]."'>".$ans_array[1]."<br>";
echo "<input type='radio' name='.$questionno.' value='".$ans_array[2]."'>".$ans_array[2]."<br>";
echo "<input type='radio' name='.$questionno.' value='".$ans_array[3]."'>".$ans_array[3]."<br><br>";
}
}
else {
echo "there is no data in database";
}
?>
<input type="submit" value = "Submit" name= "Submit" style= "width:60px; height:30px";>
</form>
</div>
</body>
$student_ans = $row['option1'];
$student_ans = $row['option2'];
$student_ans = $row['option3'];
$student_ans = $row['option4'];
Because of this, you keep pointlessly overwriting the same variable. You should only store the option they selected in $student_ans.
You may want to review your logic a bit, you're moving things in and out of arrays and different variables for no reason.
Do slight modification to form
echo "<input type='hidden' name='qno' value='".$questionno."'";
echo "<input type='radio' name='ans' value='".$ans_array[0]."'>".$ans_array[0]."<br>";
echo "<input type='radio' name='ans' value='".$ans_array[1]."'>".$ans_array[1]."<br>";
echo "<input type='radio' name='ans' value='".$ans_array[2]."'>".$ans_array[2]."<br>";
echo "<input type='radio' name='ans' value='".$ans_array[3]."'>".$ans_array[3]."<br><br>";
and then on posting form fetch them using:
$_POST['ans'] for answer field and $_POST['qno'] for question
This way you will only have the option selected by student

Get multiple form inputs values in foreach loop

I am trying to get the response of a survey, all question answers are displayed in a while loop and in action PHP page I am not getting proper responses, I'm getting the right response for the radio button only, I'm attaching the code.
<?php
$i = 1;
while ($row = mysqli_fetch_array($questions)) {
?>
<div class="control-group">
<label class="control-label" for="focusedInput">(<?php echo $i; ?>)
<?php
$questionid = $row['question_id'];
$question = $row['question'];
?>
<input type="hidden" name="questionid" value="<?php echo $questionid; ?>" />
<input type="hidden" name="question" value="<?php echo $question; ?>" />
<?php echo $row['question']; ?></label>
<div class="controls">
<?php
if ($row['answer_type'] == "Ratings") {
echo "<p>
Low<input type='radio' name='rating$i' value='1' id='rating_0'>
<input type='radio' name='rating$i' value='2' id='rating_1'>
<input type='radio' name='rating$i' value='3' id='rating_2'>
<input type='radio' name='rating$i' value='4' id='rating_3'>
<input type='radio' name='rating$i' value='5' id='rating_4'>High
</p>";
} else if ($row['answer_type'] == "Comments") {
echo "<textarea name='answer' cols='' rows=''></textarea>";
}
$i++;
echo "<br />";
?>
</div>
</div>
<?php } ?>
Action file code:
foreach($_POST as $val){
$query2 = "insert into review_details (review_id,survey_id,question_id,question,answer_rating,answer_freeresponse) values (1,$_SESSION[surveyid],$_POST[questionid],'$_POST[question]',$val,'$_POST[answer]')";
$result2 = mysqli_query($con,$query2);
if(!$result2) {
echo mysqli_error($result2);
}
}
I want to insert the survey answers in the MySQL table including the fields displayed in the output picture.
Your form tags are missing from the exposed code, so there might be some extra fields available that are important for the scenario.
There is no obvious reason for using foreach on $_POST. You should explain further why you're cycling it.
Here is some code for your action file, that might work for you:
/* create a prepared statement */
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO review_details (review_id,survey_id,question_id,question,answer_rating,answer_freeresponse) VALUES(1,?,?,?,?,?)")) {
/* bind parameters for markers */
$stmt->bind_param("sssss", $_SESSION['surveyid'], $_POST['questionid'], $_POST['question'], $val, $_POST['answer']);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}

Need to get values in textbox from database on button click in PHP

I need to get values of database in text boxes on button click using PHP and Javascript. For instance, I get values in an HTML table from a database table. I need to get the respective values in the text boxes when the user clicks on the add0 button.
Here is my code:
<form method="post" action="">
<input type="text" name="tb1" />
<input type="text" name="tb2" />
<input type="submit" name="btn" value="Find" />
</form>
<?php
include "conn.php";
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
$add_to_textbox = "<input type='button' name='btn' value='add0' />";
#****results in Grid****
echo "<table width='360px' border='1' cellpadding='2'>";
while($row = mysql_fetch_array($rs)) {
echo "<tr>";
echo "<td width='130px'>$row[Name]</td>";
echo "<td width='230px'><a href = '$row[Link]'>$row[Link]</a></td>";
echo "<td width='130px'>$add_to_textbox</td>";
echo "</tr>";
}
echo "</table>";
#**********************
mysql_free_result($rs);
?>
I need further code on button click.
imho you can use Inline edit using Ajax in Jquery
Here is it's demo
It will let you edit your displayed contents in the table itself..
Update:
<form method="post" action="">
<input type="text" name="tb1" id="tb1" />
<input type="text" name="tb2" id ="tb2" />
<input type="submit" name="btn" value="Find" />
</form>
<?php
include "conn.php";
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
$add_to_textbox = "<input type='button' name='btn' value='add0' />";
#****results in Grid****
echo "<table width='360px' border='1' cellpadding='2'>";
$rowID=1;
while($row = mysql_fetch_array($rs)) {
echo "<tr>";
echo "<td width='130px' id='name".$rowID."'>$row[Name]</td>";
echo "<td width='230px' id='link".$rowID."'><a href = '$row[Link]'>$row[Link]</a></td>";
echo "<td width='130px' onclick='txtValDisp($rowID);'>$add_to_textbox</td>";
echo "</tr>";
$rowID++;
}
echo "</table>";
#**********************
mysql_free_result($rs);
?>
<script type="text/javascript">
function txtValDisp(rowID){
var linkVal = document.getElementById('link'+rowID+'').innerHTML.replace(/<\/?[^>]+(>|$)/g, "\n");
document.getElementById("tb1").value = document.getElementById('name'+rowID+'').innerHTML;
document.getElementById("tb2").value = linkVal;
}
</script>
Recreate your form with default values taken from the database.
<form method="post" action="">
<input type="text" name="tb1" />
<input type="text" name="tb2" />
<input type="submit" name="btn" value="Find" />
</form>
<?php
include "conn.php";
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
$add_to_textbox = "<input type='button' name='btn' value='add0' />";
#****results in Grid****
echo "<table width='360px' border='1' cellpadding='2'>";
while($row = mysql_fetch_array($rs)) {
echo "<tr>";
echo "<td><input name ='INSERT_HERE' type=text value='"$row[Name]"'></td>";
echo "</tr>";
}
echo "</table>";
#**********************
mysql_free_result($rs);
?>
You just need to change the name of the object based on whatever counter of something...

issues with stick forms in PHP

i'm trying to make this form sticky but it's not doing. What i'm trying to do is that from a previous form, the user enters some parameters and the HTML table is generated to this page, while another form is displayed to edit the data in the table shown above it. But the values are not displaying in the form below.
Please help me
PLEASE FORGIVE MY FORMATING I TYPED ON A MOBILE. Thanks for you patience.
<?php session_start(); ?>
<?php require 'includes/dbconnect.php' ; ?>
<?php require 'includes/header.inc.php'; ?>
<?php
$matric_no = mysql_real_escape_string($_POST['matric_no']);
if ($_POST['matric_no'] == "")
{
echo"<div id=\"contentRight\">";
echo"<idv id=\"msg\">" ;
echo "You didn't enter a <span style=\"color:red\">Matric Number</span>";
echo"</div>";
echo"</div>";
exit();
}
$query = "SELECT matric_no
FROM students
WHERE matric_no = '$_POST[matric_no]'";
$result = mysql_query($query);
$duplicates = mysql_num_rows($result);
if ($duplicates < 1)
{
echo"<div id=\"contentRight\">";
echo"<idv id=\"msg\">" ;
echo "You dont have a record for <span style=\"color:red\">$matric_no</span>" ;
echo "</div>" ;
echo "</div>" ;
exit();
}
$result = mysql_query("SELECT matric_no, first_name, last_name, other_name
FROM students
WHERE matric_no = '".mysql_real_escape_string($_POST['matric_no'])."'") or die(mysql_error());
$number_cols = mysql_num_fields($result) ;
echo "<div id=\"contentRight\">" ;
echo "<span class=\"header\">";
echo "<p><b>Matric Number: ".mysql_real_escape_string($_POST['matric_no']) ."</b></p>";
echo "<table border = 1 , cellspacing = 0 , cellpadding = 2 bgcolor=lemonchiffon >\n";
echo "<tr align=center>\n";
for ($i=0; $i<$number_cols; $i++)
{
echo "<th>" . mysql_field_name($result, $i). "</th>\n";
}
echo "</tr>\n";
while ($row = mysql_fetch_row($result))
{
echo "<tr align=center>\n";
for ($i=0; $i<$number_cols; $i++)
{
echo "<td>";
if (!isset($row[$i]))
{echo "NULL";}
else
{echo $row[$i];}
echo "</td>\n";
}
echo "</tr>\n";
}
echo "</table>";
echo"</span>" ;
echo"</div>";
?>
<br />
<?php
while($row = mysql_fetch_array($result)){
?>
<div id="contentRight">
<p>
Select the Score options you will like to update:
<form action="student_update2.php" method="post">
<ul>
<li>Matric Number: <input type="text" name="matric_no" value="<?php echo $row['matric_no'] ; ?>"> </li><br/><br/>
<li>First Name: <input type="text" name="first_name" value="<?php echo $row['firts_name'] ; ?>"> </li><br /><br/>
<li>Last Name: <input type="text" name="last_name" value="<?php echo $row['last_name'] ; ?>"> </li><br /><br />
<li>Other Names: <input type="text" name="other_name" value="<?php echo $row['other_name'] ; ?>"</li> <br /><br />
<input type="submit" name="submit" value="Update" />
<input type="hidden" name ="submitted" value="TRUE" />
<input name="Reset" type="reset" value="Reset" />
</ul>
</div>
</div>
</form>
<?php
}
require 'includes/footer.php'; ?>
formmatting cleaned a little
Try adding this:
$result = mysql_query("SELECT matric_no, first_name, last_name, other_name
FROM students
WHERE matric_no = '".mysql_real_escape_string($_POST['matric_no'])."'") or die(mysql_error());
Above this (approx line 99):
while ($row = mysql_fetch_array($result)){
?>
<div id="contentRight">
<p>Select the Score options you will like to update:</p>
I know you have this declared once already but since you've already use while to cycle through the recordset already it may need to be reset.

How to use arrays for form input and update respective database records

I'm new to PHP... I want to know how to populate a form from mySQL. I'm stumped at the input section where I am trying to allow the user to select choices for radio button /checkbox for each record. thanks in advance for anyone's help!
TC
Here's a snippet of my code:
<?php
$mQuantity = 1;
$con = mysql_connect("localhost","t","c");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tc", $con);
/*
if request.form("itemname")<>" " then
cSQLAcct = "SELECT * FROM Restaurant_Menus WHERE Restaurant_ID='" & mRestaurant_ID & "' and Item like '%" & Request.Form("ITEMNAME") & "%' ORDER BY FOODTYPE, ITEM"
else
cSQLAcct = "SELECT * FROM Restaurant_Menus WHERE Restaurant_ID='" & mRestaurant_ID & "' ORDER BY FOODTYPE, ITEM"
end if
*/
// retrieve form data
$input = $_POST['itemname'];
echo $_POST['ITEM'];
$mItem = $_POST['ITEM'];
$mPrice = $_POST['PRICE'];
$mQuantity = $_POST['QUANTITY'];
$mOrderTotal = 0;
$mSide0 = '1';
$mOil = '1';
$mStarch = '1';
$mSalt = '1';
// use it
echo "You searched for: <i>$input</i>";
echo $mSessionID;
mysql_query("INSERT INTO OrderQueue (SessionID,item,quantity,price,no_oil,no_starch,no_salt,side0) VALUES ('$mSessionID','$mItem','$mQuantity','$mPrice','$mOil','$mStarch','$mSalt','$mSide0')");
/*
$sql="SELECT * FROM Restaurant_Menus
WHERE
Item like '%$input%'";
*/
$sql="SELECT * FROM OrderQueue
WHERE
SessionID = '$mSessionID'";
$result = mysql_query($sql);
//('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
//echo $input;
//echo $sql;
/*
if ($input!=" "){
$result = mysql_query($sql);
}
// cSQLAcct = "SELECT * FROM Restaurant_Menus WHERE Restaurant_ID='" & mRestaurant_ID & "' and Item like '%" & Request.Form("ITEMNAME") & "%' ORDER BY
else
{ $result = mysql_query("SELECT * FROM Restaurant_Menus");
}
*/
$c=1;
$class[1] = 'odd';
$class[2] = '';
$array_no_oil = array();
$array_no_salt = array();
$array_no_starch = array();
$array_rice = array();
echo "<table border='1' width=500px>
<tr>
<th></th>
<th align=left>Item</th>
<th align=right>Price</th>
<th align=right>Quantity</th>
</tr>";
//<tr onMouseOver="this.bgColor = '#F3EB49'" onMouseOut ="this.bgColor = '#DDDDDD'" bgcolor="#DDDDDD">
while($row = mysql_fetch_array($result))
{
//echo '<tr class="'.$class[$c].'" onMouseOver='#F3EB49' onMouseOut ='#DDDDDD' bgcolor="#DDDDDD" >';
//echo "<tr class='odd'>";
//echo '<tr onMouseOver="this.bgColor = '#F3EB49'" onMouseOut ="this.bgColor = '#DDDDDD'" bgcolor="#DDDDDD">'
?>
<TR onMouseover="this.bgColor='#FFC000'"onMouseout="this.bgColor='#DDDDDD'">
<?php
/*
<form action="Orders.asp" method="post" target="_top" name="LogonForm">
<td><font size = 2>
<!--<%= mQuantity %>-->
<INPUT TYPE="TEXT" NAME="QUAN" VALUE="1" SIZE=2>
</font></td>
<td width=50px><font size = 2>
<INPUT TYPE=HIDDEN NAME=ITEM VALUE="<% =mItem %>">
<INPUT TYPE=HIDDEN NAME=PRICE VALUE=<% =mPrice %>>
<INPUT TYPE=HIDDEN NAME=RID VALUE= <% =mRestaurant_ID %>>
<INPUT TYPE=HIDDEN NAME=ADDITEM VALUE = "1">
<input id="Choices" class="findit" type="submit" value ="Order" />
</form>
*/
?>
<?php
// Obtain list of images from directory
//$img = getRandomFromArray($imgList);
}
?>
<?php
if ($row['Picture']!=" "){
echo "<td><a><img src='images/".$row['Picture'].".JPG' height=50px></a></td>";
}
else{
echo "<td></td>";
}
echo "<td width=200><b>" . $row['Item'] . "</b><br>
<input class='dropwidth' type='radio' name='$array_rice' value='1' selected>White Rice<br>
<input type='radio' name='$array_rice' value='2'>Pork Fried Rice<br>
<input type='radio' name='$array_rice' value='3'>Brown Rice<br>
<input type='checkbox' name='$array_no_oil' value='1' />No Oil
<input type='checkbox' name='starch' value='no oil' />No Starch
<input type='checkbox' name='salt' value='no salt' />No Salt
</td>";
echo "<td width=50 align=right>" . number_format($row['Price'],2) . "</td>";
$mQuantity = "'" . number_format($row['Quantity'],0) . "'";
$mPrice = "'" . number_format($row['Price'],2) . "'";
$mLineItemTotal = $row['Quantity'] * $row['Price'];
$mOrderTotal = (number_format($mOrderTotal,2) + number_format($mLineItemTotal,2));
echo $mOrderTotal;
$mLineItemTotal2 = "'". number_format($mLineItemTotal,2) . "'";
//echo "<td>" . $mQuantity. "</td>";
?>
<form action="orders.php" method="post" target="_top" name="LogonForm">
<td width="50" align=right><font size = 2>
<!--<%= mQuantity %>-->
<!--<INPUT TYPE="TEXT" NAME="QUANTITY" VALUE=<?php $mQuantity; ?>>-->
<INPUT TYPE="TEXT" NAME="QUANTITY" VALUE=<?php echo $mQuantity.";" ?>/>
</font></td>
<?php echo "<td width=50 align=right>" . $mLineItemTotal . "</td>";?>
<!--<td width=50px><font size = 2>-->
<!--<INPUT TYPE="TEXT" NAME="LINEITEMTOTAL" VALUE=<?php echo $mLineItemTotal.";" ?> WIDTH=10/>-->
<INPUT TYPE=HIDDEN NAME=ITEM VALUE=<?php $mItem ?> />
<INPUT TYPE=HIDDEN NAME=PRICE VALUE=<?php $mPrice ?>/>
<INPUT TYPE=HIDDEN NAME=RID VALUE=<?php $mRestaurant_ID ?>/>
<INPUT TYPE=HIDDEN NAME=ADDITEM VALUE = "1">
<!--<input id="Choices" class="findit" type="submit" value ="Order" />-->
</form>
<?php
echo "</tr>";
if($c==2) $c=0;
$c++;
}
echo "</table>";
echo "<div>".$mOrderTotal."</div>";
mysql_close($con);
?>
You should name your HTML form elements as such: MyElement[] when using them as arrays. For example:
<form method="post" name="myForm" action="myForm.php">
<select multiple name="myFormSelectMultiple[]">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>
In this select multiple example, when the first two items are selected and then posted this form would produce similar output to the following:
array('myFormSelectMultiple' => array(1,2));
Hope this helps!

Categories