storing value from radio button to database with looping - php

I am trying now to get the value of every radio button to store in a database.
The trick is I'm using while loop to display the question and the choices.
Here is my code in displaying the questions and choices.
class questions{
function __construct(){
$db= new dbConnect();
}
public function fetchRandom()
{
$qr=mysql_query("SELECT * FROM questionaires INNER JOIN choices ON questionaires.q_id=choices.q_id WHERE RAND()<(SELECT ((10/COUNT(*))*10) FROM questionaires) ORDER BY RAND() LIMIT 10");
$c=0;
echo "<table border='3' align='center' bordercolor='#CCCCCC'>
<tr>
<th>Number:</th>
<th>Question</th>
</tr>";
while($row=mysql_fetch_array($qr))
{
$c++;
echo "<tr>";
echo "<td>" . $c . "</td>";
echo "<td>";
echo $row['question'] . "<br>";
$ans_arr=array($row['choice_a'],$row['choice_b'],$row['choice_c'],$row['choice_d']);
shuffle($ans_arr);
echo "<input type='radio' name='ans".$c."' value='".$ans_arr[0]."'>".$ans_arr[0]."</input><br>";
echo "<input type='radio' name='ans".$c."' value='".$ans_arr[1]."'>".$ans_arr[1]."</input><br>";
echo "<input type='radio' name='ans".$c."' value='".$ans_arr[2]."'>".$ans_arr[2]."</input><br>";
echo "<input type='radio' name='ans".$c."' value='".$ans_arr[3]."'>".$ans_arr[3]."</input><br>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
}
How can I store the answer of the user to database. Little help will be appreciated. Because I don't know how to code it from scratch. Thank you.

This is simple code try to code something like this.
<!DOCTYPE html>
<html>
<body>
<form method="post" action="">
<table>
<tr>
<td>Question 1</td>
<td><input type="radio" name="ques[ques1][ans1]" value="ans1" checked> Ans1
<input type="radio" name="ques[ques1][ans1]" value="ans2"> Ans2
<input type="radio" name="ques[ques1][ans1]" value="ans3"> Ans3
<input type="radio" name="ques[ques1][ans1]" value="ans4"> Ans4
</td>
</tr>
<tr>
<td>Question 1</td>
<td><input type="radio" name="ques[ques2][ans2]" value="ans1" checked> Ans1
<input type="radio" name="ques[ques2][ans2]" value="ans2"> Ans2
<input type="radio" name="ques[ques2][ans2]" value="ans3"> Ans3
<input type="radio" name="ques[ques2][ans2]" value="ans4"> Ans4
</td>
</table>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$data = $_POST['ques'];
foreach ($data as $key => $ans) {
echo 'Question :'. $key .' '. 'Answer :'. array_values($ans)[0].'<br/>';
}
}
Hope this will help you :).

Related

Refuses to get data

I am using this code to get the value of checked box in PHP but it doesn't work in the second code. The first one is just a list for testing. The second one will echo data from a database:
When applying the first code on the test list I will get the value of the box I checked but when applying it on the second part (one that gets data from database it returns Empty)
Get the checked boxes:
<?php
if(isset($_POST['DeleteCon']) )
{
if(!empty($_POST['lang']))
{
foreach($_POST['lang'] as $value)
{
echo "value : ".$value.'<br/>';
}
}
else
{
echo "value : Empty <br/>";
}
}
?>
Test list: it works on this section of the code:
<form method="post">
<?php
echo "<span>Select languages</span><br/>
<input type='checkbox' name='lang[]' value='PHP' class='table-row'> PHP <br/>
<input type='checkbox' name='lang[]' value='JavaScript'> JavaScript <br/>
<input type='checkbox' name='lang[]' value='jQuery'> jQuery <br/>
<input type='checkbox' name='lang[]' value='Angular JS'> Angular JS <br/>"
?>
</form>
But doesn't work on this one:
<form method="post">
<?php
include('database.php');
$sql = "SELECT id, ContactID ,FirstName, LastName, Phone FROM Contact WHERE ID='1'";
$result = $conn->query($sql);
if ( !empty($result->num_rows) && $result->num_rows > 0) { // ...
// output data of each row
echo "<form method='post'>";
while($row = $result->fetch_assoc()) {
echo "<tr>
<td id='delete'>
<input type='checkbox' name='lang[]' value='PHP' class='table-row'>
</td>
<td>". $row["FirstName"]. "</td>
<td>". $row["LastName"]. "</td>
<td>". $row["Phone"] ."</td></tr>";
}
echo "</form>";
} else {
echo "<tr>
<td id='delete'>
<input type='checkbox' id='row1' class='table-row'>
</td>
<td> 0 results </tr>";
}
$conn->close();
?>
</form>

Select option not passing values [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My select option is not passing values. I don't know why this isn't working any help would be appreciated but i have no idea what is going on.
HTML/PHP
if(isset($_POST['submit'])){ $Name = isset($_POST['name']) ? trim($_POST['name']) :''; echo "
<a href='index.php'>
<-- Your Home Page</a>
</br>
</br>"; echo "
<table border='1'>
<form action='' method='post'>
<tr>
<th>Name</th>
<th>Car</th>
<th>Night</th>
<th>Siteid</th>
<th>Date</th>
<th>LHA</th>
<th>AAS</th>
<th>LS</th>
<th>Update</th>
</tr>"; $sql = "SELECT * FROM data WHERE Name = '$Name' ORDER BY Date"; $sth = $pdo->query($sql); while($row = $sth->fetch()) { $Car = $row['Car']; echo "
<form action='' method='post'>"; echo "
<tr>"; echo "
<td>" . $row['Name']. "</td>"; echo "
<td>
<input type='text' name='Car' placeholder='".$row[' Car ']."' value=''>
</td>"; echo "
<td>
<input type='text' name='Car' placeholder='".$row[' Night ']."' value=''>
</td>"; echo "
<td>
<input type='text' name='Car' placeholder='".$row[' Siteid ']."' value=''>
</td>"; echo "
<td>
<input type='text' name='Car' placeholder='".$row[' Date ']."' value=''>
</td>"; echo "
<td>
<input type='text' name='Car' placeholder='".$row[' LHA ']."' value=''>
</td>"; echo "
<td>
<input type='text' name='Car' placeholder='".$row[' AAS ']."' value=''>
</td>"; echo "
<td>
<input type='text' name='Car' placeholder='".$row[' LS ']."' value=''>
</td>"; echo "
<input type='hidden' name='PID' value='".$row[' PID ']."' />"; echo "
<td>
<input type='submit' name='submit' value='".$row[' PID ']."' />
</td>"; echo "</tr>"; echo "</form>"; } echo "</table>"; $pdo = NuLL; }Else{ Echo "Pick a user"; } ?>
HTML Form
<form action="" method="POST">
<select name="name" id="name">
<?php foreach ($data as $row): ?>
<option value="<?=$row['user_id']?>">
<?=$row[ "user_name"]?>
</option>
<?php endforeach ?>
</select>
<input type="submit" value="submit">
</form>
Its because you have no value in your option tag
try this
<form action="" method="post">
<select name="name" id="name">
<?php foreach ($data as $row): ?>
<option value="<?php=$row["user_name"]?>"> <?php echo $row["user_name"]?></option>
<?php endforeach ?>
</select>
<input type="submit" value="submit">
</form>
and use php tag like this its better , instead what you are using at the moment
$Name = isset($_POST['name']) ? trim($_POST['name']) :'';
<?php echo $row["user_name"]?>// i dont know why you have this line here
and to display the result
<?php echo $Name;?>
Use this way please:
<option value="<?=$row["user_name"]?>"> <?=$row["user_name"]?></option>
You have to set the value to post. Like this:
<option value="<?=$row["user_name"]?>"> <?=$row["user_name"]?></option>
If you want to use the value inside the <option> tags, you have to remove the property value="". Your line become:
<option><?=$row["user_name"]?></option>
the property value="something" is useful when you want to display some "human readable" information but send something more usable for your system.
Typically, you can display user_name (what you put inside the tags), and send user_id like this:
<option value="<?=$row['user_id']?>"><?=$row["user_name"]?></option>

keep data in form when clicking submit

EDIT: Apologies - all code now pasted below
Apologies for the first time newbie question - I've been looking for an answer here and on google - I get the feeling this is some simple coding i'm messing up.
I've created a form which, when you validate, you check all the data on the same page and the original data is kept in the original form so you can make changes if you wish.
I have a section of the form where this doesn't work however - where you can ask multiple questions and each question can have up to 4 answers.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<head>
<title>Test page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="stylenewtest.css" type="text/css" />
<script language="javascript" src="tableadd.js"></script>
</head>
<body>
<?php
$string = isset($_POST['quiz_format']) ? $_POST['quiz_format'] : false;
$quiz_format = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $string);
$stringquiz_100 = isset($_POST['quiz_100']) ? $_POST['quiz_100'] : false;
$quiz_100 = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $stringquiz_100);
$stringquiz_fback = isset($_POST['quiz_fback']) ? $_POST['quiz_fback'] : false;
$quiz_fback = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $stringquiz_fback);
$stringquiz_title = isset($_POST['quiz_title']) ? $_POST['quiz_title'] : false;
$quiz_title = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $stringquiz_title);
$stringquiz_instruct = isset($_POST['quiz_instruct']) ? $_POST['quiz_instruct'] : false;
$quiz_instruct = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\?,\"\'\._#\\/ !&()=\+;:\t\r\n-]", "", $stringquiz_instruct);
$stringquiz_time = isset($_POST['quiz_time']) ? $_POST['quiz_time'] : false;
$quiz_time = ereg_replace("[^0-9a-zA-Z?ąćęłńóśżźĄĆĘŁŃÓŚŻŹ\. ]", "", $stringquiz_time);
?>
<div id="content">
<p><span class="error">* required field.</span></p>
<form method="post" action="">
<div class="datagrid">
<table>
<tr><th colspan="2">Please choose the format of the quiz<span class="error">*</span></th></tr>
<tr><td>Hangman</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Hangman") echo "checked";?> value="Hangman"></td></tr>
<tr><td>Gap fill</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Gap fill") echo "checked";?> value="Gap fill"></td></tr>
<tr><td>Multiple choice</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Multiple Choice") echo "checked";?> value="Multiple choice"></td></tr>
<tr><td>Simple Q & A</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Simple Q & A") echo "checked";?> value="Simple Q & A"></td></tr>
<tr><td>Word formation hangman</td><td><input type="radio" name="quiz_format" <?php if (isset($quiz_format) && $quiz_format=="Word formation hangman") echo "checked";?> value="Word formation hangman"></td></tr>
</table>
</div>
<br />
<div class="datagrid">
<table>
<tr><th colspan="2">Continue repeating the exercise until 100% achieved?<span class="error">*</span></th></tr>
<tr><td>Yes</td><td><input type="radio" name="quiz_100" <?php if (isset($quiz_100) && $quiz_100=="Yes") echo "checked";?> value="Yes"></td></tr>
<tr><td>No</td><td><input type="radio" name="quiz_100" <?php if (isset($quiz_100) && $quiz_100=="No") echo "checked";?> value="No"></td></tr>
</table>
</div>
<br />
<div class="datagrid">
<table>
<tr><th colspan="2">Show the answer as correct/incorrect after every question or just at the end?<span class="error">*</span></th></tr>
<tr><td>After every question</td><td><input type="radio" name="quiz_fback" <?php if (isset($quiz_fback) && $quiz_fback=="After every question") echo "checked";?> value="After every question"></td></tr>
<tr><td>Just at the end</td><td><input type="radio" name="quiz_fback" <?php if (isset($quiz_fback) && $quiz_fback=="Just at the end") echo "checked";?> value="Just at the end"></td></tr>
</table>
</div>
<br />
<div class="datagrid">
<table>
<tr><th colspan="2">Please enter in the title of the quiz<span class="error">*</span></th></tr>
<tr><td>Quiz title:</td><td><input type="text" name="quiz_title" value="<?php echo $_POST[quiz_title];?>"></td></tr>
</table>
<br />
<table>
<tr><th colspan="2">Please enter in the instructions for the quiz<span class="error">*</span></th></tr>
<tr><td>Quiz instructions:</td><td><textarea name="quiz_instruct" rows="10" cols="40"><?php echo $_POST[quiz_instruct];?></textarea></td></tr>
</table>
</div>
<br />
<div class="datagrid">
<script language="javascript">
window.onload = moreFields;
window.onload = init;
</script>
<table>
<tr><th colspan="5">Please enter in the quiz's questions and answers:<span class="error">*</span></th></tr>
</table>
<div id="readroot" style="display: none">
<input type="button" value="Remove a question field"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
<table>
<tr>
<td>Question:</td>
<td colspan="3"><input type="text" name="q[]" value="<?php echo $_POST['q'][$i] ?>"></td>
</tr>
<tr>
<td>Answer 1:</td>
<td>Answer 2:</td>
<td>Answer 3:</td>
<td>Answer 4:</td>
</tr>
<tr>
<td><input type="text" name="a1[]" value="<?php echo $_POST['a1'][$i] ?>"></td>
<td><input type="text" name="a2[]" value="<?php echo $_POST['a2'][$i] ?>"></td>
<td><input type="text" name="a3[]" value="<?php echo $_POST['a3'][$i] ?>"></td>
<td><input type="text" name="a4[]" value="<?php echo $_POST['a4'][$i] ?>"></td>
</tr>
</table>
</div>
<span id="writeroot"></span><input type="button" id="moreFields" value="Click here to add further question fields" /><br />
</div>
<br />
<div class="datagrid">
<table>
<tr><td><input type="submit" name="Submit1" value="Submit"/></td></tr>
</table>
</div>
</form>
<?php
if ( isset( $_POST['Submit1'] ) ) {
echo "<form method=post action=insert.php>";
echo "<h1>Please confirm the quiz details are correct</h1>";
echo "<div class=datagrid>";
echo "<table>";
if(empty($string)){
echo("<tr><td>Quiz format:</td><td><h3>Please go back and choose a quiz format<h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Quiz format:</td><td>" . $quiz_format . "</td></tr>");
echo("<input type=hidden name=quiz_format value='" . $quiz_format . "' />");
}
if(empty($stringquiz_100)){
echo("<tr><td>Continue repeating the exercise until a 100% score is achieved?:</td><td><h3>Please go back and choose an option<h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Continue repeating the exercise until a 100% score is achieved?:</td><td>" . $quiz_100 . "</td></tr>");
echo("<input type=hidden name=quiz_100 value='" . $quiz_100 . "' />");
}
if(empty($stringquiz_100)){
echo("<tr><td>Do you want the answer to be shown after every question or at the end of the quiz?:</td><td><h3>Please go back and choose an option<h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Do you want the answer to be shown after every question or at the end of the quiz?:</td><td>" . $quiz_fback . "</td></tr>");
echo("<input type=hidden name=quiz_fback value='" . $quiz_fback . "' />");
}
echo "</table>";
echo "</div>";
echo "<br />";
echo "<div class=datagrid>";
echo "<table>";
if(empty($stringquiz_title)){
echo("<tr><td>Quiz title:</td><td><h3>Please go back and enter in a title for the quiz</h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Quiz title:</td><td>" . $quiz_title . "</td></tr>");
echo("<input type=hidden name=quiz_title value='" . $quiz_title . "' />");
}
if(empty($stringquiz_instruct)){
echo("<tr><td>Quiz instructions:</td><td><h3>Please go back and enter in instructions for the quiz</h3></td></tr>");
$showbutton=1;
}
else{
echo("<tr><td>Quiz instructions:</td><td>" . $quiz_instruct . "</td></tr>");
echo("<input type=hidden name=quiz_instruct value='" . $quiz_instruct . "' />");
}
echo "</table>";
echo "</div>";
echo "<br />";
echo "<div class=datagrid>";
echo "<table>";
if(empty($stringquiz_time)){
echo("<tr><td>Time limit:</td><td>not specified</td></tr>");
}
else
{
echo("<tr><td>Time limit:</td><td>" . $quiz_time . "</td></tr>");
echo("<input type=hidden name=quiz_time value='" . $quiz_time . "' />");
}
echo "</table>";
echo "</div>";
echo "<br />";
echo "<div class=datagrid>";
echo "<table>";
echo "<tr><td colspan=5>The questions and answers to your quiz:</td></tr>";
$aq = $_POST['q'];
$aa1 = $_POST['a1'];
$aa2 = $_POST['a2'];
$aa3 = $_POST['a3'];
$aa4 = $_POST['a4'];
$N = count($aq);
for($i=1; $i < $N; $i++){
if($aq[$i]==""){
echo("<tr><td>Question:</td><td><h3>Please go back and enter a question</h3></td></tr>");
$showbutton=1;
}
elseif($aa1[$i]==""){
echo("<tr><td>Answer:</td><td><h3>Please go back and enter at least one answer</h3></td></tr>");
$showbutton=1;
}
else{
echo ("<table><tr><td>Question:</td><td colspan=3>" . $aq[$i]. "<input type=hidden name=q[] value='" . $aq[$i] . "'></td></tr>
<tr><td>Answer 1:</td><td>Answer 2:</td><td>Answer 3:</td><td>Answer 4:</td></tr>
<tr><td>" .$aa1[$i] . " <input type=hidden name=a1[] value='" .$aa1[$i] . "'></td>
<td>" .$aa2[$i] . " <input type=hidden name=a2[] value='" .$aa2[$i] . "'></td>
<td>" .$aa3[$i] . " <input type=hidden name=a3[] value='" .$aa3[$i] . "'></td>
<td>" .$aa4[$i] . " <input type=hidden name=a4[] value='" .$aa4[$i] . "'></td> </tr></table>");
}
}
echo "</table>";
echo "</div>";
echo "<br />";
echo "<div class=datagrid>";
echo "<table>";
echo "<tr><td><input type=button value='<< Go Back' onclick='goBack()' /></td></tr>";
if ($showbutton =="1"){
}
else{
echo "<tr><td><input type=submit value=Submit></td></tr>";
echo "</table>";
echo "</form>";
}
}
?>
</div>
</body>
</html>
but every time I submit, the questions and answers carry through but the form fields lose all the data. How can I keep the data in the fields?
Many thanks in advance
You can simply set the value of the input to either $_POST['old_value_name] or $_GET['old_value_name'] depending on which form method you are using. Therefore, your new code would look something like this (assuming that you are looking for the key $i from your question):
<table>
<tr>
<td>Question:</td>
<td colspan="3"><input type="text" name="q[]" value="<?php echo $_POST['q'][$i] ?>"></td>
</tr>
<tr>
<td>Answer 1:</td>
<td>Answer 2:</td>
<td>Answer 3:</td>
<td>Answer 4:</td>
</tr>
<tr>
<td><input type="text" name="a1[]" value="<?php echo $_POST['a1'][$i] ?>"></td>
<td><input type="text" name="a2[]" value="<?php echo $_POST['a2'][$i] ?>"></td>
<td><input type="text" name="a3[]" value="<?php echo $_POST['a3'][$i] ?>"></td>
<td><input type="text" name="a4[]" value="<?php echo $_POST['a3'][$i] ?>"></td>
</tr>
</table>
As far as I've understood your problem you want to keep values in a form after they were sent to server. "I've created a form which, when you validate, you check all the data on the same page and the original data is kept in the original form so you can make changes if you wish"
It's ok. I remember I wanted the same a few months ago. This is why I tried to help.
There is only a problem that after pressing "submit" button form is sent to server and page is reloaded.
In return you get a new page from webserver which you pointed in the form field "action".
I would do it so:
Target form: <br/>
<form id="target" action="index.php" method='post'>
<input name="first_field" type="text" value="<?php if ( isset($_POST['first_field']) )
echo $_POST['first_field']; ?>" /> <br/>
<input name="second_field" type="text" value="<?php if ( isset($_POST['second_field']))
echo $_POST['second_field'];?>" /> <br/>
<p><b>What kind of girls do you like?:</b><Br>
<input type="radio" name="browser" value="brunette" <?php if( $_POST['browser']==="brunette" ) echo "checked"; ?> > brunette<Br>
<input type="radio" name="browser" value="blonde" <?php if( $_POST['browser']==="blonde" ) echo "checked"; ?> > blonde<Br>
<input type="radio" name="browser" value="red" <?php if( $_POST['browser']==="red" ) echo "checked"; ?> > red<Br>
</p>
<input type="submit" />
</form>
Any ideas how it can be changed/improved are encouraged.

How to generate a table using data from database and for loop (php)

I am trying to fetch some data from my database and then iterate over the result to generate a table that looks like the one shown below. I'm still quite new to php/html so pls bear with my coding abilities. I have the following code so far:
<?php
if (isset($_POST['vote'])) {
echo "
<table id='myTable' class=''>
<thead>
<tr>
<th>i</th>
<th>Importance</th>
<th>How Much More</th>
</tr>
</thead>
<tbody>";
$getObs = $db->prepare("SELECT ComplianceID, ObstacleDescription FROM obstacles WHERE ComplianceID = :option");
$getObs->bindParam(':option', $option);
$getObs->execute();
$result = $getObs->fetchAll();
for ($i=0; $i < $result; $i++) {
echo '<tr id="'.$result['ObstacleDescription'][$i].'">';
echo '<td class = "aObs">'.$result[$i].'</td>
<td class = "aObs">'."<input type='radio' name='op1' value='1'>"
.$result['ObstacleDescription'][$i]."<?php echo "or"?>"; "<input type='radio' name='op2' value='2'>"
.$result['ObstacleDescription'][$i+1].</td>'
<td class="aObs"><input type='radio' name='op1' value='1'>
<input type='radio' name='op2' value='2'>
<input type='radio' name='op3' value='3'>
<input type='radio' name='op4' value='4'>
<input type='radio' name='op5' value='5'>
<input type='radio' name='op6' value='6'>
<input type='radio' name='op7' value='7'>
<input type='radio' name='op8' value='8'>
<input type='radio' name='op9' value='9'>
</td>';
}
echo"</tbody>";
}
?>
In this example I have the values: Security, Finaicial, Legal and Technical as my ObstacleDescription in db. Each is compared with the next on each row and the last one is compared with the first. If anyone could pls point me in the right direction from here. Thanks in advance
You can clean this up a lot if you close PHP and get rid of all quotes with echo
<?php
if (isset($_POST['vote'])) {
?> // It's a lot easier to just close PHP instead of dealing with single and double quotes
<table id='myTable' class=''>
<thead>
<tr>
<th>i</th>
<th>Importance</th>
<th>How Much More</th>
</tr>
</thead>
<tbody>
<?php
$getObs = $db->prepare("SELECT ComplianceID, ObstacleDescription FROM obstacles WHERE ComplianceID = :option");
$getObs->bindParam(':option', $option);
$getObs->execute();
$result = $getObs->fetchAll();
for ($i=0; $i < $result; $i++): ?> // This saves you a lot of hassle, again, with quotes.
<td class="aObs"><input type='radio' name='op1' value='1'>
<input type='radio' name='op2' value='2'>
<input type='radio' name='op3' value='3'>
<input type='radio' name='op4' value='4'>
<input type='radio' name='op5' value='5'>
<input type='radio' name='op6' value='6'>
<input type='radio' name='op7' value='7'>
<input type='radio' name='op8' value='8'>
<input type='radio' name='op9' value='9'>
</td>
When you're inside the for() loop, you can just use <?php echo result['whatever']; ?> arbitrarily if you want to put something inside each <td>. I imagine this is what you will want to do eventually.
Try Below code:
<?php
if (isset($_POST['vote'])) {
echo "
<table id='myTable' class=''>
<thead>
<tr>
<th>i</th>
<th>Importance</th>
<th>How Much More</th>
</tr>
</thead>
<tbody>";
$getObs = $db->prepare("SELECT ComplianceID, ObstacleDescription FROM obstacles WHERE ComplianceID = :option");
$getObs->bindParam(':option', $option);
$getObs->execute();
$result = $getObs->fetchAll();
for ($i=0; $i < $result; $i++) {
echo "<tr id='".$result['ObstacleDescription'][$i]."'>";
echo "<td class = 'aObs'>".$result[$i]."</td>
<td class = 'aObs'><input type='radio' name='op1' value='1'>
".$result['ObstacleDescription'][$i]." or <input type='radio' name='op2' value='2'>
".$result['ObstacleDescription'][$i+1]."</td>
<td class='aObs'>
<input type='radio' name='op1' value='1'>
<input type='radio' name='op2' value='2'>
<input type='radio' name='op3' value='3'>
<input type='radio' name='op4' value='4'>
<input type='radio' name='op5' value='5'>
<input type='radio' name='op6' value='6'>
<input type='radio' name='op7' value='7'>
<input type='radio' name='op8' value='8'>
<input type='radio' name='op9' value='9'>
</td>";
}
echo "</tr></tbody>";
}
?>

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