Getting radio button value and storing in php - php

this is radio button code
now what if radio button does not have a constant name how would i store the data in database because to store the data in database we will need a name of form attribute
$sql1="select * from questions where email='". $_SESSION['email'] ."'";
$row=mysqli_query($conn,$sql1);
while ($result = mysqli_fetch_array($row))
{
?>
<h2 id="question_<?php echo $result['qid'];?>"><?php echo $result['qid'].".".$result['question'];?></h2>
<input type="radio" value="<?php echo $result['answer1'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer1'];?>
<input type="radio" value="<?php echo $result['answer2'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer2'];?>
<input type="radio" value="<?php echo $result['answer3'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer3'];?>
<input type="radio" value="<?php echo $result['answer4'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer4'];?>
if we know the name of radio button we can access it using
<input type="radio" value="<?php echo $result['answer4'];?>" name="name"><?php echo $result['answer4'];?>
$name=$_POST['name'];
but in the above code name of radio button is not fixed.questions is the table which consists of qid and questions with multiple options that is answer1,answer2 etc
i want to store the option select by user into database.for which i need to know the name of radio button
how should i use post in this case
$name=$_POST['what should go in here'];

You can get the radio button value along with question ID as:
Basic Example:
<?php
$array = array(1,2); // your Question ID array
?>
Your Form:
<form method="post" action="">
<?php
foreach ($array as $key => $qid) {
?>
<input type="radio" value="1" name="radio[<?=$qid?>]">
Answer 1
<input type="radio" value="2" name="radio[<?=$qid?>]">
Answer 2
<input type="radio" value="3" name="radio[<?=$qid?>]">
Answer 3
<input type="radio" value="4" name="radio[<?=$qid?>]">
Answer 4
<?php
echo "<br/>";
}
?>
<input type="submit" name="submit">
</form>
In PHP:
<?php
if(isset($_POST['submit'])) {
$query = array();
foreach ($_POST['radio'] as $key => $value) {
$query[] = "('$value','$key')";
}
$sql = "INSERT INTO table (answer,questionID) VALUES ";
$sql .= implode(",", $query);
echo $sql;
}
?>
In this example query look like:
INSERT INTO table (answer,questionID) VALUES ('2','1'),('3','2')
Few Suggestions:
- Your code is open for SQL Injection, you must need to prevent your code with SQL Attack and this reference will help you to understand: How can I prevent SQL injection in PHP?
- Make sure your column name and table name not having any conflict, currently, you are using same name for both.
Update with Your Code:
<?php
while ($result = mysqli_fetch_array($row))
{
?>
<h2 id="question_<?php echo $result['qid'];?>"><?php echo $result['qid'].".".$result['question'];?></h2>
<input type="radio" value="<?php echo $result['answer1'];?>" name="radio[<?php echo $result['qid'];?>]">
<?php echo $result['answer1'];?>
<input type="radio" value="<?php echo $result['answer2'];?>" name="radio[<?php echo $result['qid'];?>]">
<?php echo $result['answer2'];?>
<input type="radio" value="<?php echo $result['answer3'];?>" name="radio[<?php echo $result['qid'];?>]">
<?php echo $result['answer3'];?>
<input type="radio" value="<?php echo $result['answer4'];?>" name="radio[<?php echo $result['qid'];?>]">
<?php echo $result['answer4'];?>
<?
}
?>
In PHP:
<?php
if(isset($_POST['submit'])) {
$query = array();
foreach ($_POST['radio'] as $key => $value) {
$query[] = "('$value','$key')";
}
$sql = "INSERT INTO table (answer,questionID) VALUES ";
$sql .= implode(",", $query);
echo $sql; // run this query in mysqli_query()
}
?>
Few More Instructions:
- Change the table name as per your table name
- Change the column name according to your column.
- Use INSERT query at once, no need to use it inside the loop.

Create an array at the end of while loop like this :
while ($result = mysqli_fetch_array($row))
{
?>
<h2 id="question_<?php echo $result['qid'];?>"><?php echo $result['qid'].".".$result['question'];?></h2>
<input type="radio" value="<?php echo $result['answer1'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer1'];?>
<input type="radio" value="<?php echo $result['answer2'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer2'];?>
<input type="radio" value="<?php echo $result['answer3'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer3'];?>
<input type="radio" value="<?php echo $result['answer4'];?>" name="<?php echo $result['qid'];?>"><?php echo $result['answer4'];?>
<? $names[] = $result['qid'];
}
if(isset($_POST['submit'])) {
for ($i=0; $i<count($names); $i++) {
if(isset($_POST[$names[$i]]) {
$rate = $_POST[$names[$i]];
$sql ="INSERT INTO answer (answer, qid) VALUES (".$rate.", ".$names[$i] .")";
mysqli_query($con, $sql);
}
}
}
?>

Related

Send values to db when multiple checkboxes are checked

I am loading some data from a db table to checkboxes. When a user checks boxes and submits, the values from these checkboxes need to be added to a different table. With the code I have now, I am able to send values of one checked box. What am I missing in sending the values of all the checked checkboxes?
<table>
<?php
$q5=mysqli_query($link,"SELECT * FROM brands_offer WHERE Brand_Id='$bid' AND Published='1' ");
while($row5 = mysqli_fetch_array($q5)){
$catid= $row5['Catg_Id'];
$subcatid= $row5['Subcatg_Id'];
$pid= $row5['Product_Id'];
?><tr><td>
<form action="store-admin.php?search=<?php echo $stname;?>#stock" method="post">
<input type="checkbox" name="checkbox" value="<?php echo "$bname,$catid,$subcatid,$pid";?>" >
<?php
echo $bname;
echo " -> ";
echo $catid;
echo ", ";
echo $subcatid;
echo ", ";
echo $pid;
echo " ";
}
?></td></tr>
<input type="submit" value="Save Changes" name="add" >
</form>
</table>
<?php
if(isset($_POST['add']))
{
$chk = $_POST['checkbox'];
$val = explode(",",$chk);
$bn = $val[0];
$cid= $val[1];
$scid= $val[2];
$prid= $val[3];
echo "<script type='text/javascript'>alert('brand: ". $bn."')</script>";
echo "<script type='text/javascript'>alert('cat: ". $cid."')</script>";
echo "<script type='text/javascript'>alert('sub: ". $scid."')</script>";
echo "<script type='text/javascript'>alert('pr: ". $prid."')</script>";
}?>
Use brackets in your checkbox name attribute name="checkbox[]" and your post variable will be an array of selected values.
Edit: I noticed you have form opening tag inside the while loop. You need to put it before while loop otherwise its generating tons of opening form tags.
So it looks like you have only one checkbox. If you want to POST the values of all the checkboxes as an array I believe you need to add [] to the name of your input field. So:
<input type="checkbox" name="checkbox[]" value="<?php echo "$bname";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$catid";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$subcatid";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$pid";?>"/>
Hopefully I understood your question.

All checkboxes are checking out

I've got a question.
I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php if($room->trained == 1) { ?> <input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]"> <input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked> <?php echo "Y"; } else{ ?> <input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]"> <?php echo "N"; }?> </td>
<Td><?php if($room->active == 1) { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked> <?php echo "Active"; } else { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" <?php echo "Inactive"; } ?>
I used the "trick" with the input type hidden, but it is checking out all checked checkboxes..
Thanks in advance!

Dynamic radio button with self-post using PHP & MySQL

I'm drawing data from a MySQL database that dynamically places a question with 4-5 radio button choices for the answer. These radio buttons all belong to the same group, $quest_name. The first pass of the while statement will create 4 radio buttons belonging to radio group "question_1".
It creates 30-40 of these questions on a page, each with 4 radio buttons. I want the user to fill in all there answers and the page to post back to itself with the users answers still selected and then display if they were correct or not (functionality I still have to add).
I'm trying to follow http://www.w3schools.com/php/php_form_complete.asp as an example, but use a dynamically created radio button name instead.
This is what I have thus far:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$quest_num = $row["id"];
$question = $row["question"];
$option_1 = $row["option_1"];
$option_2 = $row["option_2"];
$option_3 = $row["option_3"];
$option_4 = $row["option_4"];
$option_5 = $row["option_5"];
$answer = $row["answer"];
$quest_name = "question_" . $row["id"];
echo "(" . $quest_num . ") " . $question . "<br>";
?>
<label>
<input type="radio" name=<?php echo $quest_name ?>
<?php if (isset(echo $quest_name) && echo $quest_name == echo $option_1) echo "checked"; ?>
value=<?php echo $option_1 ?>><?php echo $option_1 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_2 ?>><?php echo $option_2 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_3 ?>><?php echo $option_3 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_4 ?>><?php echo $option_4 ?>
</label>
<br>
<br>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit">
</form>
The part causing me grief so far is:
<?php if (isset(echo $quest_name) && echo $quest_name == echo $option_1) echo "checked"; ?>
I have also tried:
<?php if (isset($quest_name) && $quest_name == $option_1) echo "checked"; ?>
and:
<?php echo (isset($quest_name) && $quest_name == $option_1) ? "checked" : ""; ?>
How do you post back to the same page what they've selected? Like in this case I'm trying to say if "question_1" is set and "question_1" is equal to "converter" (the first radio button option) then have it checked when submit button is clicked.
I'm not that good at web development, but I'm trying to create a website to help my fellow electrical technician classmates.
Thanks for any help.
EDIT :
Using this line of code fixed the issue:
<?php if(isset($_POST[$quest_name]) && $_POST[$quest_name]==$option_1) { echo 'checked="checked"'; } ?>
What you need is called Radio Group. In HTML layer it is created with same name for all and different values for each like this:
<p>
<label>
<input type="radio" name="RadioGroup1" value="Value1" id="RadioGroup1_0">
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Value2" id="RadioGroup1_1">
Radio</label>
<br>
</p>
And when you want to get the user input in php layer you go like this:
<?php
//check if Radio Group 1 is set
if(isset($_POST['RadioGroup1'])) {
// print the value of Radio Group 1 choice
echo $_POST['RadioGroup1'];
}
?>
When you want to create a Selected Radio in HTML layer you go like this:
<input name="RadioGroup1" type="radio" id="RadioGroup1_1" value="radio" checked="checked">
So you have to check if user inputs the value of which radio like this:
<label>
<input type="radio" name="RadioGroup1" value="value1" id="RadioGroup1_0" <?php if(isset($_POST['RadioGroup1']) && $_POST['RadioGroup1']=='value1') { echo ' checked="checked"'; } ?>>
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="value2" id="RadioGroup1_1" <?php if(isset($_POST['RadioGroup1']) && $_POST['RadioGroup1']=='value2') { echo ' checked="checked"'; } ?> >
Radio</label>
You could use the following:
<input type="radio" name="<?php echo $quest_name ?>" value="<?php echo $option_1 ?>"
<?php if (isset($quest_name) && ($quest_name == $option_1)) echo "checked"; ?> />

radio button in while loop

i am coding a page for the attendance of students and in the page all the students name are retrieved dynamically from database using while loop and inside the while loop i have used a radio button.
my problem is the radio button work's correctly but i am unable to insert the value of radio buttons into database.here is my code :
include'connection.php';
#$id = mysql_real_escape_string($_GET['id']);
$res=mysql_query("SELECT * FROM `std_register` AS p1 ,`sims-register-course` AS p2 WHERE p2.semester=p1.std_semester and p2.department=p1.std_department and p2.id = '".$id."'");
if ($res==FALSE) {
echo die(mysql_error());
}
while ($row=mysql_fetch_assoc($res)) { ?>
<input type="hidden" id="dept_0" name="dept[]" value="<?php echo $row["department"] ?>">
<input type="hidden" id="course_name_1" name="course_name[]" value="<?php echo $row["course_name"] ?>">
<input type="hidden" id="std_semester_2" name="std_semester[]" value="<?php echo $row["semester"] ?>">
<input type="hidden" id="std_id_3" name="std_id[]" value="<?php echo $row["id"] ?>">
<input type="hidden" id="std_name_4" name="std_name[]" value="<?php echo $row["std_name"] ?>">
<tr>
<td class =info><?php echo $row["std_name"];?></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="1"></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="2"></td>
</tr>
<?php }?>
</table><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<input type="submit" name="submit" value="Assign" class="btn btn-large btn-block btn-primary"></div></div>
</form>
<?php
for ($i=0; $i < 4; $i++) {
if(isset($_POST["submit"])) {
$stdid = mysql_real_escape_string($_POST['std_id'][$i]);
$dptname = mysql_real_escape_string($_POST['dept'][$i]);
$courseName = mysql_real_escape_string($_POST['course_name'][$i]);
$stdSemester = mysql_real_escape_string($_POST['std_semester'][$i]);
$std_name = mysql_real_escape_string($_POST['std_name'][$i]);
$present = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $present;
$insrt = mysql_query("INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$present',0,0)") or die(mysql_error());
}
}
and is it possible to insert values from this radio buttons to two columns of database?
I am not sure but try to add 'checked' property in radio input
<input type="radio" name="<?php echo "status[".$row["std_name"]."]" ?>" value="1" checked></td>
Or
use Select tag instead of radio button
EDIT
use this code to insert in present column or absent column
$value = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $value;
if($value == 1) //check if present
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$value',0,0)";
}
else //if absent
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester',0,'$value',0)";
}
$insrt = mysql_query($sql) or die(mysql_error());

PHP - Loop number of selected check boxes on form submit

I have an issue where I need to loop the number of check boxes on a form submit. Foreach check box that is looped I need to then insert data into the database.
How Would I go about looping over the amount of check boxes that have being passed via form submit?
My code is as follows:
Form:
<form action="createChallenge.php" method="post" name="chalCreate">
Challenge Name:<input type="text" name="chalName" />
<br />
Challenge Target:<input type="text" name="chalTarget"/>
<br />
End Date:<input type="text" name="chalDate">
<br />
<!-- Needs a jquery datepicker -->
Select Friends: <br />
<?php
$selFriend = $conn->prepare("SELECT * FROM Friends WHERE UserID = '$userID' AND Friend = 'y' ORDER BY FriendName ASC");
$selFriend->execute();
foreach($selFriend as $row){
?>
<input type="checkbox" name="test" value="<?php echo $row['FriendID'] ?>"><?php echo $row['FriendName'] ?><br>
<?php
}
?>
<br />
<button type="submit">Create Challenge</button>
</form>
PHP to handle the form:
<?php
if(isset($_POST['test']))
{
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
echo $name = $_POST['chalName'];
echo $target = $_POST['chalTarget'];
echo $date = $_POST['chalDate'];
echo $friend = $_POST['test'];
echo $setby = $_COOKIE['userID'];
$create = $conn->prepare("INSERT INTO Challenge ( chalSetBy, chalName, chalTarget, chalDate ) VALUES ('$setby', '$name', '$target', '$date') ");
$create->execute();
if($create)
{
echo "Challenge made successfully";
}
else
{
echo "There was a problem";
}
}
?>
I thought doing the following would echo out data, but it didn't, it only selected the last check box:
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
Make an array of your checkbox in HTML page like as below,
<form name="frm" method="post">
<input type="checkbox" value="1" name="test[]">
<input type="checkbox" value="2" name="test[]">
<input type="checkbox" value="3" name="test[]">
<input type="checkbox" value="4" name="test[]">
<input type="checkbox" value="5" name="test[]">
<input type="checkbox" value="6" name="test[]">
<input type="submit">
</form>
<?php
foreach($_POST['test'] as $key=>$value)
{
echo $value."<br>";
}

Categories