I want to store related activities of services
<form method='post' id='userform' action='arrayvalue.php'>
<tr>
<td>Trouble Type</td>
<br>
<td>
<input type='checkbox' name='servicevar[]' value='tds'>tds<br> <br>
<input type='checkbox' name='activityvar[]' value='One'>Return<br>
<input type='checkbox' name='activityvar[]' value='Two'>Filling<br>
<br>
<input type='checkbox' name='servicevar[]' value='Gst'>Gst<br> <br>
<td>
<input type='checkbox' name='activityvar[]' value='One'>Return<br>
<input type='checkbox' name='activityvar[]' value='Two'>Filling<br>
<br>
</td>
</tr>
</table> <input type='submit' name="submit" class='buttons'>
</form>
<?php if(isset($_POST[submit]) {
$activity = $_POST['activityvar'];
$service = $_POST['servicevar'];
foreach ($service as $key => $value) {
echo ($value);
echo "<br>";
foreach ($activity as $key => $value) {
echo ($value);
echo "<br>";
}
}
}
MY OUTPUT:
tds
one
two
one
two
Gst
one
two
one
two
Expected Output:
tds
one
two
Gst
one
two
Try to use One foreach loop with index's like :
if(isset($_POST[submit]) {
$activity = $_POST['activityvar'];
$service = $_POST['servicevar'];
$index = 0;
foreach ($service as $key => $value) {
echo $value;
echo $activity[$index]; $index++;
echo $activity[$index]; $index++;
}
}
EDIT : To store the data in your database, use the same concept like :
if(isset($_POST[submit]) {
$activity = $_POST['activityvar'];
$service = $_POST['servicevar'];
$index = 0;
$nbr_of_related_activities = 2;
foreach ($service as $key => $value) {
$servicevalue = $value;
for ($i=0; $i<$nbr_of_related_activities;$i++) {
$activityvalue = $activity[$index+$i];
$query = "insert into serviceacitivitymap(service_id,activity_id) values('$servicevalue','$activityvalue')";
$insert_row = $conn->query($query) or die ($conn->error.__LINE__);
}
$index += $nbr_of_related_activities;
}
}
Related
I have a form that outputs:
Quiz_Assign_ID (Combines User_ID with Quiz ID)
Question ID
Checkboxes for inputting the response (Option A, Option B, Option C)
<div class="Main">
<form method="post" action="LP_Quiz_Student_Quiz_Responses.php">
<?php
$quiz_id = trim($_GET['quiz_id']);
$quiz_assign_id = trim($_GET['quiz_assign_id']);
$i = 1;
$count=1;
$sel_query=("SELECT Quiz.quiz_id, Quiz.quiz_title, Quiz_Questions.quiz_id, Quiz_Questions.quiz_question_id, Quiz_Questions.question, Quiz_Questions.option1, Quiz_Questions.option2, Quiz_Questions.option3, Quiz_Questions.answer FROM Quiz, Quiz_Questions WHERE (Quiz.quiz_id=Quiz_Questions.quiz_id) and (Quiz.quiz_id=?)");
$stmt = $conn->prepare($sel_query);
$stmt->bind_param("i", $quiz_id);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows === 0) exit('No Quiz Questions!');
while($row = $result->fetch_assoc()) { ?>
<p></p>
<p> </p>
<table>
<tr>
<td>
</td>
<td>
<input name="quiz_assign_id" type="hidden" value=" <?php echo $quiz_assign_id; ?>" /> <input name="quiz_question_id" type="hidden" value=" <?php echo $row["quiz_question_id"]; ?>" /></td>
<td> </td>
</tr>
<tr>
<td>
<h4>Question <?php echo $i++; ?> </h4>
</td>
<td>
<h4><?php echo $row["question"]; ?> </h4>
</td>
<td> </td>
</tr>
<tr>
<td>
<h4>A</h4>
</td>
<td><?php echo $row["option1"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option A" style="width: 20px" /></td>
</tr>
<tr>
<td>
<h4>B</h4>
</td>
<td><?php echo $row["option2"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option B" /></td>
</tr>
<tr>
<td>
<h4>C</h4>
</td>
<td><?php echo $row["option3"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option C" /></td>
</tr>
</table>
<?php
}
?>
<input name="Submit1" type="submit" value="submit" />
</form>
</div>
Upon submission I run the following script, which captures the response but does not get the question_id and Quiz_Assign_ID and does not update the values in the database:
<?php
if(!empty($_POST['Response'])) {
foreach ($_POST['Response'] as $value) {
$quiz_assign_id=trim($_POST['quiz_assign_id']);
$quiz_question_id=$_POST['quiz_question_id'];
echo 'Answer'; echo $value;
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
$stmt = $conn -> prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
if (
$stmt &&
$stmt -> bind_param('sss', $value, $quiz_assign_id, $quiz_question_id) &&
$stmt -> execute() &&
$stmt -> affected_rows === 1
) {
echo "<script>
alert('Responses submitted!');
window.history.go(-2);
</script>";
} else {
echo"<script>
window.history.go(-2);
</script>";
}
}
}
?>
I have been playing with it for hours, but with no luck.
Because you are using check boxes en not radio buttons, you should change your input checkbox name attribute, so it's sending a nested array with the question ID as a key and the answers array as the value, like so: (notice the extra []) Also $quiz_question_id is not defined, you should use the $row array.
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
Because the response array is now nested, the question answers are grouped by question_id. To iterate over the nested response array, use the following for loop:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
}
So your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
echo 'Answers'; print_r($values); // Values is an array here.
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
// Because $values is an array, transform it into a comma separated string to insert them into the database
// But you could also make a database table with answers and loop over the $values array.
$value = implode(', ', $values);
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $value, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
To accommodate both type of questions with check boxes and questions with radio buttons, you can use the same response code, but first check if its an array before transforming it into a string.
Questions with radio buttons, one answer per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>]" type="radio" value="Option A" style="width: 20px" /></td>
Questions with check boxes, multiple answers per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
And now your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
// If it's an array (checkbox), transform to string.
// Else it is already a string (radio).
if (is_array($values)) {
$values = implode(', ', $values);
}
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $values, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('".$done." Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
But with above code you can accommodate all kind of field types.
To put it simple:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// Check if array, it's a checkbox or multiple select question
if (is_array($answered)) {
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
} else {
// radio, hidden, input, select or textarea question
echo "Answered: ".$answered."<br />";
}
}
I hope this points you in the right direction.
I am trying to submit this radio buttons but it shows this
Notice: Array to string conversion in C:...
i don't really know what to do to make it work.
I've to try some other ways but its not working
<?php
public function userQuestion($type)
{
$option = $this->con->prepare("SELECT * FROM stem_questions WHERE category = :type");
$option->bindParam(':type', $type);
$option->execute();
$id = array();
while ($row = $option->fetch()) {
$id[] = $row["id"];
$que[] = $row["question"];
$o1[] = $row["opt1"];
$o2[] = $row["opt2"];
$o3[] = $row["opt3"];
$o4[] = $row["opt4"];
$cat[] = $row["category"];
$isa[] = $row["is_anwer"];
}
$count = count($id);
if ($count < 1) {
echo "<span class='alert alert-info fa fa-warning col-lg-12' style='color:orange; font-size:14px; color: white'> You have not Set any Question Yet.</span>";
} else {
$k = 0;
echo "";
for ($i = 1, $j = 0; $i <= $count; $i++, $j++) {
$k++;
echo "<form method='POST'> <p><strong> Question $i : $que[$j]</strong></p> <div class='form-group'> <input type='hidden' name ='qust' value='$que[$j]'> <input type='hidden' name ='cat' value='$cat[$j]'><input type='hidden' name ='ans' value='$isa[$j]'> <input type='radio' name ='opt[$k]' value='$o1[$j]'> <label class='form-check-label'>  $o1[$j]</label><br> <input type='radio' name='opt[$k]' value='$o2[$j]'><label class='form-check-label'>  $o2[$j]</label><br> <input type='radio' name='opt[$k]' value='$o3[$j]'><label class='form-check-label'>  $o3[$j]</label><br> <input type='radio' name ='opt[$k]' value='$o4[$j]'> <label class='form-check-label'>  $o4[$j]</label><br> </div> </form> ";} } }
public function submitQuiz()
{
//FOR THE QUIZ SYSTEM
if (isset($_POST["submit"])) {
for ($i = 1; $i <= 5; $i++) {
$userid = $_SESSION['id'];
$qid = $_POST['qust'];
$uans = $_POST['opt'] . $i;
$ans = $_POST['ans'];
$category = $_POST['cat'];
$insert = $this->con->prepare("INSERT INTO user_question_answer (user_id, question_id, user_ans, is_right, type)VALUES (:userid, :qid, :uans, :ans, :category)");
$insert->bindParam(':userid', $userid);
$insert->bindParam(':qid', $qid);
$insert->bindParam(':uans', $uans);
$insert->bindParam(':ans', $ans);
$insert->bindParam(':cat', $cat);
if (!$insert->execute()) {
$atry = $insert->errorInfo();
echo $atry[2];
exit();
} else {
// this just my person function #return $this->just_notify("<strong>Successfully uploaded </strong>", 1);} } } }
it was suppose to submit but its just bringing up errors
Error is with your name tag radio option in form.
Replace your echo "" part --
with
echo "<form method='POST'>
<p><strong> Question $i : $que[$j]</strong></p>
<div class='form-group'>
<input type='hidden' name ='qust' value='$que[$j]'>
<input type='hidden' name ='cat' value='$cat[$j]'>
<input type='hidden' name ='ans' value='$isa[$j]'>
<input type='radio' name ='opt1['.$k.']' value='$o1[$j]'> <label class='form-check-label'>  $o1[$j]</label><b`enter code here`r>
<input type='radio' name='opt2['.$k.']' value='$o2[$j]'><label class='form-check-label'>  $o2[$j]</label><br>
<input type='radio' name='opt3['.$k.']' value='$o3[$j]'><label class='form-check-label'>  $o3[$j]</label><br>
<input type='radio' name ='opt4['.$k.']' value='$o4[$j]'> <label class='form-check-label'>  $o4[$j]</label><br>
</div>
</form>"
and
$insert->bindParam(':uans', $uans); can bind only single value not the array data.
> <input type="radio" name="radio_name[]"
> value="id_of_row_from_database_or_identity_of_this_radio_button" />
>
> ex:-
>
> <input type="radio" name="age[]" value="G`enter code here`G101" />12 <input
> type="radio" name="age[]" value="GG102" />23
i have 5 of these:
if(isset($_POST['checkbox'])) {
$name = "Alex";
}
How can I echo the name of every selected checkbox outside of the if statement?
From your example, build an array of $name:
if(isset($_POST['checkbox'])) {
$name[] = "Alex";
}
if(isset($_POST['checkbox1'])) {
$name[] = "Bob";
}
Then either:
echo implode(', ', $name);
Or:
foreach($name as $value) {
echo $value;
}
But actually I'm wondering why not just set the values in the form inputs (use an array):
<input type="checkbox" name="checkbox[]" value="Alex">
<input type="checkbox" name="checkbox[]" value="Bob">
Then:
foreach($_POST['checkbox'] as $value) {
echo $value;
}
i have a php file like this
<form action='#' method='POST'>
<p>
<input type='checkbox' name='interest[]' value="music">music
<input type='checkbox' name='interest[]' value="reading book">reading book
<input type='checkbox' name='interest[]' value="coding">coding
</p>
<input type='submit' name='send'><br/>
</form>
i tried to foreach loop to output the selected values. However it always output "Array";
<?php
foreach($_POST as $keys =>$values)
{
echo $values."<br/>";
}
?>
<?php
if (isset($_POST))
{
foreach($_POST as $keys1 =>$values1)
{
if (count($values1) > 0)
{
foreach($values1 as $keys2 =>$values2)
{
echo $values2."<br/>";
}
}
}
}
?>
I was trying to make a COMPUTERIZED ORDERING SYSTEM. My problem is how can I compute the 1st value on my checkbox. The second value on the checkbox will be posted on the summary of orders.
Once I've check all those three, it will compute the total amount of the menu and to display the selected menu on the summary of orders. But I can't figure out how can I display the total amount.
Can anybody guide me how to compute the total on my 1st value on the checkbox?
<form method="post">
<input name='ts[]' type='checkbox' value='40 |Tosilog'/> Tosilog
<br>
<input name='cs[]' type='checkbox' value='40 |Chiksilog'/>Chiksilog
<br>
<input name='ps[]' type='checkbox' value='45 |Porksilog'/>Porksilog
<br>
<input type="submit" name="go" value= "Total">
</form>
<?php
//tosilog
$ts = $_POST['ts'];
$value = explode("|",$ts[0]);
echo $value[0];
echo $value[1];
//chiksilog
$cs = $_POST['cs'];
$value = explode("|",$cs[0]);
echo $value[0];
echo $value[1];
//porksilog
$ps = $_POST['ps'];
$value = explode("|",$ps[0]);
echo $value[0];
echo $value[1];
?>
<!-- compute for the 1st value on checkbox -->
<?php
$ts=$_POST['ts[0]'];
$cs=$_POST['cs[0]'];
$ps=$_POST['ps[0]'];
?>
<?php $compute = $ts[0] + $cs[0] + $ps[0];?>
<?php echo "$compute " ; ?>
If you're getting an array of checkbox elements, and they are numeric, you can use array_sum(). Not sure I understand your suggested structure, but I'll give you a code sample here based on the existing form structure. Then I'll post another bit to try to make this simpler for you. Executive summary: You do not need all the variables that are created by this form structure.
<?php // RAY_temp_user193.php
error_reporting(E_ALL);
$total = 0;
$inputs = array();
$errors = array();
if (!empty($_POST))
{
if (!empty($_POST['ts']))
{
foreach ($_POST['ts'] as $ts)
{
$inputs[] = current(explode(' |', $ts));
}
}
else
{
$errors[] = 'Tosilog';
}
if (!empty($_POST['cs']))
{
foreach ($_POST['cs'] as $cs)
{
$inputs[] = current(explode(' |', $cs));
}
}
else
{
$errors[] = 'Chiksilog';
}
if (!empty($_POST['ps']))
{
foreach ($_POST['ps'] as $ps)
{
$inputs[] = current(explode(' |', $ps));
}
}
else
{
$errors[] = 'Porksilog';
}
// IF ERRORS
if (!empty($errors))
{
echo 'UNABLE TO PRINT COMPLETE TOTAL. MISSING: ' . implode(',', $errors);
}
$total = array_sum($inputs);
if ($total) echo "<br/>TOTAL: $total <br/>" . PHP_EOL;
// END OF THE ACTION SCRIPT
}
// CREATE THE FORM
$form = <<<ENDFORM
<form method="post">
<input name='ts[]' type='checkbox' value='40 |Tosilog'/> Tosilog
<br>
<input name='cs[]' type='checkbox' value='40 |Chiksilog'/>Chiksilog
<br>
<input name='ps[]' type='checkbox' value='45 |Porksilog'/>Porksilog
<br>
<input type="submit" value= "Total">
</form>
ENDFORM;
echo $form;
See http://www.laprbass.com/RAY_temp_miggy.php
This is probably more along the lines of the way I would do it. The script knows what goes into the HTML and it knows exactly what to expect in the POST request. It is easy to add or remove different inputs. Often these kinds of inputs come from a data base table.
<?php // RAY_temp_miggy.php
error_reporting(E_ALL);
$total = 0;
// EXPECTED INPUTS
$inputs = array
( 'Tosilog' => 40
, 'Chiksilog' => 40
, 'Porksilog' => 45
)
;
if (!empty($_POST))
{
// ACTIVATE THIS TO SEE WHAT WAS SUBMITTED
// var_dump($_POST);
// SUM OF THE ELEMENTS
$total = array_sum($_POST);
echo "TOTAL: $total";
// SUM OF THE EXPECTED INPUTS
$expect = array_sum($inputs);
if ($total != $expect) echo " BUT THERE MAY BE INCOMPLETE INPUTS!";
// END OF THE ACTION SCRIPT
}
// CREATE THE FORM
$checkboxes = NULL;
foreach ($inputs as $name => $value)
{
$checkboxes
.= '<input name="'
. $name
. '" type="checkbox" value="'
. $value
. '" />'
. $name
. '<br/>'
. PHP_EOL
;
}
$form = <<<ENDFORM
<form method="post">
$checkboxes
<input type="submit" value= "Total">
</form>
ENDFORM;
echo $form;