please help, i'm developing an online quiz application. All the questions and answers will be selected from the database. Where i'm having probkem with is to get the values from the radio button whether checked or not. bellow is the code that generate the questions and answers from database.
if (!isset($_POST['submit'])) {
echo "<form method=post action='#'>";
echo "<table border=0>";
while ($row = mysql_fetch_array($display)) {
$id = $row["id"];
$question = $row["question"];
$opt1 = $row["ans1"];
$opt2 = $row["ans2"];
$opt3 = $row["ans3"];
$opt4 = $row["ans4"];
$opt5 = $row["ans5"];
$answer = $row["ans"];
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><td>$opt5 <input type=radio name=q$id value=\"$opt5\">q$id</td></tr>";
}
echo "</table>";
echo "<input type='submit' value='See how you did' name='submit'>";
echo "</form>";
}
the name of the radio button is
<input type='radio' name='q$id' value='$opt4' />
How do i get the value of the checked radio button?
or is my PHP code wrong?
what i needed is to output what is selected if a radio button is checked.
if(isset($_POST['submit']))
{
$value = $_POST[''];//the value of the radio button, i don't know what to put here
$n = count($value);
for($i=0; $i < $n; $i++)
{
echo $value[$i];
}
}
Try:
if(isset($_POST['submit']))
{
$value = $_POST;//the value of the radio button, i don't know what to put here
$n = count($value);
for($i=0; $i < $n; $i++)
{
echo $value[$i];
}
}
$_POST[''] was wrong. You needed to use just $_POST.
You could also just use foreach here:
if(isset($_POST['submit']))
{
$values = $_POST;//the value of the radio button, i don't know what to put here
foreach($values as $value)
{
echo $value;
}
}
$_POST is just a array containing whatever your form submited. If you had a name textfield you would use:
echo $_POST['name'];
to echo it.
Try
var_dump("<PRE>", $_POST);
And you will see exactly how your form is being organised. Link to documentation
thanks for your response. i was able to come out with this code and it works but i don't know if the structure or the way i solved it is proper or good enough.
<?php
if (!isset($_POST['submit'])) {
echo "<form method=post action='#'>";
echo "<table border=0>";
while ($row = mysql_fetch_array($display)) {
$id = $row["id"];
$question = $row["question"];
$opt1 = $row["ans1"];
$opt2 = $row["ans2"];
$opt3 = $row["ans3"];
$opt4 = $row["ans4"];
$opt5 = $row["ans5"];
$answer = $row["ans"];
echo "<tr><td colspan=3><br><b>$question</b></td></tr>";
echo "<tr><td><input type=radio name=$id value=\"$id $opt1\">$opt1 </td><td><input type=radio name=$id value=\"$id $opt2\">$opt2 </td><td><input type=radio name=$id value=\"$id $opt3\">$opt3 </td><td><input type=radio name=$id value=\"$id $opt4\">$opt4 </td><td><input type=radio name=$id value=\"$id $opt5\">$opt5 <br>";
}
echo "</table>";
echo "<input type='submit' value='See how you did' name='submit'>";
echo "</form>";
}
?>
what i did was to include the id of the question in the value of the radio button
<input type=radio name=$id value=\"$id $opt1\">
i collect the values of the radio button using $_POST as suggested, i then explode the value into two arrays so the first array will contain the question id and the second will contain the actual value of the radio button (answer).
<?php
elseif (isset($_POST['submit']))
{
var_dump("<PRE>", $_POST);
$sd = $_POST;
foreach($sd as $sd)
{
$tok = explode(" ", $sd, 2);
$w = mysql_query("select * from `questions` WHERE `id` = '$tok[0]'")or die(mysql_error());
if(mysql_num_rows($w) == 1)
{
$sf = mysql_fetch_object($w);
echo $tok[1].".......".$sf->ans."<br>";
}
}
}
?>
it works perfectly but will it give efficient result?
Related
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)
I want to Create a Shoping Cart on PHp,
The Code is simple, When the customer fill the QTY and click button Add to cart, the code will save the PRoduct ID and Qty to a Cart Table. But the problem is that Form inside the Looping. And How Can I Get ID and Qty only from The button that Customer Click.
The Program look like this
And The Script Like This
<?php
if(isset($_POST[ADD]))
{
$qty = $_POST[QTY];
$harga = $_POST[HARGA_ASLI];
$id = $_POST[ID];
print_r($_POST);
}
$kolom = 3;
$sql = "SELECT *,FORMAT(harga,0)AS harga_digit FROM item";
$hasil = mysql_query($sql);
echo "<form method=POST action=index.php>";
echo "<table>
<tr>";
$i = 0;
while($data=mysql_fetch_array($hasil))
{
if($i >= $kolom)
{
echo "</tr><tr>";
$i = 0;
}
$i++;
echo "<td align='center'><br><a href='detailBarang.php?ID=$data[ID]'><img src='$data[img]' width='200' height='150'/><br>$data[nama_produk]</a><br>
Rp. $data[harga_digit]<br>
<input type='submit' name='ADD' id='ADD' value='Add to Cart'>
<input type='text' name='QTY' id='QTY' placeholder='Qty' /><br>
<input type='hidden' name='HARGA_ASLI' id='HARGA_ASLI' value='$data[harga]' /><br>
<input type='hidden' name='ID' id='ID' value='$data[ID]' />
<br></td>";
}//end of while
echo "<tr></table>";
echo "</form>";
?>
If i fill the Qty and click Add to Cart, only the last Item can Post The Data.
How To Post The data Only for Customer Choose?
Im very Appreciated Your Answer.
Thanks
First, let's convert your MySQL to MySQLi. More explanation inside the comments /* */:
<?php
$connection=mysqli_connect("YourHost","YourUsername","YourPassword","NameofYourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$res=mysqli_query($con,"SELECT * FROM item");
while($row=mysqli_fetch_array($res)){
$nameofsubmitbutton=$row['ID'];
if(isset($_POST[$nameofsubmitbutton])){
$nameofproduct=$row['namaproduk'];
$nameofnumbersubmitted=$nameofsubmitbutton."number";
$quantity=$_POST[$nameofnumbersubmitted];
if(empty($quantity)){
echo "You wanted to buy a ".$nameofproduct."?<br>Type in a number so you can add it to your cart.";
}
else {
mysqli_query($connection,"INSERT INTO yourTable ('','') VALUES ('$quantity','$nameofproduct')");
echo "You bought ".$quantity." of ".$nameofproduct;
}
} /* END OF IF ISSET */
} /* END OF WHILE LOOP $RES */
$kolom = 3;
$hasil = mysqli_query($connection,"SELECT *,FORMAT(harga,0) AS harga_digit FROM item"); /* YOU SURE WITH THIS QUERY? */
echo "<form method=POST action=''>"; /* SUBMIT ON ITSELF */
echo "<table><tr>";
$i = 0; /* THIS WOULD ALSO SET AS YOUR COUNTER */
while($data=mysqli_fetch_array($hasil))
{
$id=$data['ID'];
if($i >= $kolom){
echo "</tr><tr>";
$i = 0;
} /* END OF IF $i >= $KOLOM */
$i++;
echo "<td align='center'><br><a href='detailBarang.php?ID=$data[ID]'><img src='$data[img]' width='200' height='150'/><br>".$data[nama_produk]."</a><br>Rp. ".$data[harga_digit]."<br>"; /* IF TO ECHO VARIABLES, USE ".$variable." */
$numbername=$id."number";
echo "<input type='number' name='$numbername' id='QTY' placeholder='Qty' /><br>"; /* CHANGE YOUR INPUT TYPE TO NUMBER */
/* NO NEED FOR THE HIDDEN INPUT */
echo "<input type='submit' name='$id' id='ADD' value='Add to Cart'></td>"; /* CHANGE THE NAME OF SUBMIT BUTTON TO THE CORRESPONDING ID FROM YOUR TABLE */
} /* END OF WHILE LOOP */
echo "<tr></table>";
echo "</form>";
?>
I tried it on my local computer. You should too.
Here's a sample screen shot.
This may do the trick:
<?php
$kolom = 3;
$sql = "SELECT *,FORMAT(harga,0)AS harga_digit FROM item";
$hasil = mysql_query($sql);
while($data=mysql_fetch_array($hasil))
{
if(isset($_POST['ADD'.$data[ID]]))
{
$qty = $_POST['QTY'.$data[ID]];
$harga = $_POST['HARGA_ASLI'.$data[ID]];
$id = $_POST['ID'.$data[ID]];
print_r($_POST);
}
}
echo "<form method=POST action=index.php>";
echo "<table>
<tr>";
$i = 0;
while($data=mysql_fetch_array($hasil))
{
if($i >= $kolom)
{
echo "</tr><tr>";
$i = 0;
}
$i++;
echo "<td align='center'><br><a href='detailBarang.php?ID=$data[ID]'><img src='$data[img]' width='200' height='150'/><br>$data[nama_produk]</a><br>
Rp. $data[harga_digit]<br>
<input type='submit' name='ADD'".$data[ID]." id='ADD' value='Add to Cart'>
<input type='text' name='QTY'".$data[ID]." id='QTY' placeholder='Qty' /><br>
<input type='hidden' name='HARGA_ASLI'".$data[ID]." id='HARGA_ASLI' value='$data[harga]' /><br>
<input type='hidden' name='ID' id='ID'".$data[ID]." value='$data[ID]' />
<br></td>";
}//end of while
echo "<tr></table>";
echo "</form>";
?>
I have a table that has different names of competences and another one in which we have the competence_ID and the user_ID that has that competence. I have a form in which I submit the competences that apply to a certain user. Now, I want to retrieve these competences and check boxes in case they are valid.
I use this code, but it does not seem to work.
<?php
include "db.php";
$employees=mysql_query("SELECT * FROM asiakas");
echo "<form method='post' action='' id='employeesselection'><select name='select_employee' id='select_employee'>";
while($row=mysql_fetch_array($employees)){
$selected = ($row['Id'] == $_POST['select_employee'])?'selected="selected"':'';
echo '<option '.$selected.' value="'.$row['Id'].'">'.$row['Etunimi'].' - '. $row['Sukunimi'].'</option>';
}
echo "</select><input type='hidden' name='action' value='selectedemployee'>
<input type='submit' value ='submit' name='submit'><br/>";
if(isset($_POST['select_employee'])){
$specific=mysql_query("SELECT Id, Sukunimi,Etunimi from asiakas WHERE Id=".$_POST['select_employee']);
$sp=mysql_fetch_array($specific);
}
if(isset($sp['Etunimi']) && isset($sp['Sukunimi'])){
$comp=mysql_query("SELECT * FROM Competences");
echo "<br/>select competences for: ". $sp['Etunimi'];
$id= $sp['Id'];
$result=mysql_query("SELECT distinct c_ID from User_Competence WHERE e_ID=".$id);
while($test=mysql_fetch_array($result))
{
echo $test['c_ID'];
}
echo "<table><th>valid?</th><th>Competence description</th>";
$counter=0;
$traverse=0;
while($compi=mysql_fetch_array($comp)){
$checked='';
if($test[$traverse]==$counter){
$checked="checked";
$traverse++;
}
$counter ++;
echo "<tr><td><input type='checkbox'" .$checked." name='c[]' value='".$compi['Competence_ID']."'></td><td>".$compi['Competence_Description']."</td></tr>";
}
echo "</table>";
echo "<input type='hidden' name='action' value='selectchecked'>";
echo "<input type='submit' value='submit checks'>";
}
if(isset($_POST) && !empty($_POST)){
print_r($_POST);
}
if(isset($_POST['action']) && $_POST['action']='selectchecked'){
if (isset($_POST['c'])){
$s = $_POST['c'];
foreach ($s as $k => $v) {
if (is_array($v)) {
// array_push($s, implode('', array($v [$what])));
}
};
echo $abc= implode(',', $s);
for ( $a=0;$a<count($s);$a++){
$ar=explode(',',$abc);
echo $var= $ar[$a];
$q=mysql_query("INSERT INTO user_competence(c_ID, e_ID) VALUES ('".$var."','".$id."')");
}
}
}
echo "</form>";
?>
If you put checked as an attribute on the <input type="checkbox"> it will be checked, even if you leave the actual value of the attribute empty.
So change the following parts from...
$checked="checked";
...
echo "<tr><td><input type='checkbox' checked='".$checked."' name='c[]' ...
Into...
$checked="checked='checked'";
...
echo "<tr><td><input type='checkbox' ".$checked." name='c[]' ...
Which will mean if the $test[$traverse$] is true, checked='checked' will be placed into the HTML, otherwise it will be left out.
This is my code to display list of questions and 4 options( using option box). user has to select the correct option . Is it possible to store the user selected options in array variable. There may be 10 to 20 questions array variable should contain only option values.
<?php
require('connect.php');
$display=mysql_query("SELECT * FROM Java_Test_1 ORDER BY id ASC");
echo "<form method=post action=$PHP_SELF>";
echo "<table border=0>";
while ($row = mysql_fetch_array($display))
{
$id=$row['0'];
$question=$row['1'];
$opta=$row['2'];
$optb=$row['3'];
$optc=$row['4'];
$optd=$row['5'];
$answer = $row["woptcode"];
echo "<tr><td colspan=3><br><b>$question</b></td></tr>";
echo "<tr><td>$opta<input type=radio name=$id value='a'></input></td><td>$optb <input type=radio name=$id value='b'></input></td><td>$optc <input type=radio name=$id value='c'> </input></td><td>$optd <input type=radio name=$id value='d'></input></td></tr>";
}
echo "</table>";
echo "<input type='submit' value='start' name='doo'>";
echo "</form>";
}
$name = 'opt';
$counter = 0;
while ($row = mysql_fetch_array($display))
{
$name = 'opt'.$counter;
$counter++;
$id=$row['0'];
$question=$row['1'];
$opta=$row['2'];
$optb=$row['3'];
$optc=$row['4'];
$optd=$row['5'];
$answer = $row["woptcode"];
echo "<tr><td colspan=3><br><b>$question</b></td></tr>";
echo "<tr><td>$opta<input type=radio name=$name value='a'></td>
<td>$optb <input type=radio name=$name value='b'></td>
<td>$optc <input type=radio name=$name value='c'></td>
<td>$optd <input type=radio name=$name value='d'></td>
</tr>";
}
Here is the official documentation that expains this in detail
http://php.net/manual/en/faq.html.php
Section: How do I create arrays in a HTML ?
I have a PHP script that allows users to enter grades by selecting a radio button that corresponds to the students grade. It allows them to view the selected grades before they can be finally submitted. I also want the page to have the ability to go back to the selection page and remember the radio buttons that were selected so that the user doesn't have to set all of them again when going back. Here is what I have coded so far, it takes the user back to selection page but doesn't restore the radio button selection.
<?php
session_start();
$script_name = $_SERVER["PHP_SELF"];
if(!isset($_SESSION["course"]) || !isset($_SESSION["course"])) {
$_SESSION["course"] = $_POST["coursename"];
$_SESSION["section"] = $_POST["section"];
}
if(($_SESSION["authenticated"] == true || isset($_POST["back"])) && !isset($_POST["continue"])) {
$course = $_SESSION["course"];
$section = $_SESSION["section"];
$file_name = $course.$section.".txt";
$_SESSION["filename"] = $file_name;
// Open file containing student names.
$fp = fopen($_SESSION["filename"], "r") or die("Could not open file");
$students = array();
$i = 0;
echo "<h2>Grades Submission Form</h2>";
echo "<h2>Course: $course, Section: $section</h2>";
echo "<form action=\"$script_name\" method='post'>";
echo "<table border='1'>";
while (!feof($fp)) {
$line = trim(fgets($fp));
$students[$i++] = $line;
echo "<tr><td>$line</td>";
echo "<td><input type='radio' name=\"$line\" value='A'/>A</td>";
echo "<td><input type='radio' name=\"$line\" value='B'/>B</td>";
echo "<td><input type='radio' name=\"$line\" value='C'/>C</td>";
echo "<td><input type='radio' name=\"$line\" value='D'/>D</td>";
echo "<td><input type='radio' name=\"$line\" value='F'/>F</td>";
echo "</tr>";
}
echo "</table><br>";
echo "<input type='submit' name='continue'/>";
echo "</form>";
} elseif($_SESSION["authenticated"] == true && isset($_POST["continue"]) && !isset($_POST["back"])) {
unset($_POST["continue"]);
$keys = array_keys($_POST);
$values = array_values($_POST);
echo "<h2>Grades to Submit</h2>";
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Grade</th></tr>";
for($i = 0; $i < count($keys); $i++) {
echo "<tr><td>{$keys[$i]}</td><td>{$values[$i]}</td></tr>";
}
echo "</table><br>";
echo "<form action='confirmation.php' method='post'>";
echo "<input type='submit' value='Submit Grades'/>";
echo "</form>";
echo "<form action=\"$script_name\" method='post'>";
echo "<input type='submit' value='Back'/>";
echo "</form>";
} else {
header("Location: main.php");
}
?>
You could serialize() an array containing the radio button states and store it in your session. When you go back, all you have to do is unserialize it and set the data again.