I have made an edit form on a bunch of checkboxes and a textbox.
Here is my code
<?php
require("config.php");
$id = $_GET['id'];
$sql = "SELECT * FROM contracts WHERE id= '$id'";
$result = $con->query($sql);
while ($row = $result->fetch_assoc())
{
$subunit = explode(',',$row['subunit']);
?>
<form action="" method="GET">
ID: <?php echo $id; ?><br>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
Sub-Category Unit:
<input type="checkbox" name="subunit[]" value="OFL" <?php in_array('OFL', $subunit) ? print "checked" : ""; ?>>OFL
<input type="checkbox" name="subunit[]" value="HVTL" <?php in_array('HVTL', $subunit) ? print "checked" : ""; ?>>HVTL
<input type="checkbox" name="subunit[]" value="PINS" <?php in_array('PINS', $subunit) ? print "checked" : ""; ?>>PINS
<input type="checkbox" name="subunit[]" value="FEG" <?php in_array('FEG', $subunit) ? print "checked" : ""; ?>>FEG
<input type="checkbox" name="subunit[]" value="PC" <?php in_array('PC', $subunit) ? print "checked" : ""; ?>>PC
<input type="checkbox" name="subunit[]" value="PI" <?php in_array('PI', $subunit) ? print "checked" : ""; ?>>PI<br>                              
Others:
<input type="text" name="subunit[]" value="<?php echo $row['subunit']; ?>"/>
<br><br>
<input type="submit" name="edit" value="Update" />
</form>
<?php
}
if(isset($_GET['edit']) ){
$subunit = isset($_GET ['subunit']) ? implode(",", $_GET['subunit']) :null;
$upd= "UPDATE `contracts` SET `subunit` = '$subunit' WHERE `id` = '$id'";
if($do_upd = $con->query($upd)) {
echo "Update Success<br>";
echo "$upd <br>";
echo "$do_upd <br>";
echo "<a href='viewcheck.php?id=$id'>View</a>";
} else {
echo "Update Fail<br>";
echo "$upd <br>";
echo "$do_upd <br>";
echo "<a href='viewcheck.php?id=$id'>View</a>";
}
}
?>
The code is working fine. When I went back to the edit form again after I have updated the data, it looks something like this.
I don't want all the checkbox values to be displayed in the textbox. Yet I want to use the same attribute for both checkbox and textbox. How do I do this?
Inside the while loop below the line $subunit = explode(',',$row['subunit']); need to place this code:
$array_all=array('OFL','HVTL','PINS','FEG','PC','PI');
$a=array_values(array_diff($subunit,$array_all));
$a will give you the values for Others text field. You need to replace the value of Others as:
<input type="text" name="subunit[]" value="<?php echo $a[0]; ?>"/>
Related
So, I have made a code to edit radio buttons, drop down lists and text boxes.
The Division->(dropdown list and Other: textbox) and External->(textbox) are under the same "client_details".
This is the example of the edit form.
This is the code I made.
<?php
require("config.php");
$id = filter_input(INPUT_GET, 'id');
?>
<html>
<head>
<title> Edit a Contract </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
ID: <input type="hidden" name="id" value="<?php echo $id; ?>" />
<?php
$sql = "SELECT * FROM contracts WHERE `id` = $id";
$result = $con->query($sql);
$row = $result->fetch_assoc();
$client_type = $row['client_type'];
?>
<label for = "client1">
<input type="radio" name="client_type" id = "client1" value="Division" <?php echo ($client_type == 'Division')? "checked" : "" ?> onclick="toggleDivision()"/> Division
</label>
                                     
<label for ="client2">
<input type="radio" name="client_type" id = "client2" value="External" <?php echo ($client_type == 'External')? "checked" : "" ?> onclick="toggleExternal()"/> External
</label>
 
<input type="text" id="extText" name="client_details2" value="<?php echo $row['client_details']; ?>" disabled />
<br><br>
<div id="division">
Division:
<select id="mySelect" name="client_details" onclick="enableTextbox()" disabled>
<option value="Choose" <?php echo $row['client_details'] == 'Choose' ? "selected" : ""; ?> />Choose Division...</option>
<option value="Distribution" <?php echo $row['client_details'] == 'Distribution' ? "selected" : ""; ?> />Distribution</option>
<option value="Transmission" <?php echo $row['client_details'] == 'Transmission' ? "selected" : ""; ?> />Transmission</option>
<option value="Generation" <?php echo $row['client_details'] == 'Generation' ? "selected" : ""; ?> />Generation</option>
<option value="Procument" <?php echo $row['client_details'] == 'Procument' ? "selected" : ""; ?> />Procument</option>
<option value="Other" <?php echo $row['client_details'] == 'Other' ? "selected" : ""; ?> />Others</option>
</select>
<br><br>
Others:<input type="text" id="otherTxt" name="client_details1" value="<?php echo $row['client_details']; ?>" disabled />
<br>
</div>
<br>
<input type="submit" name="submit" value="Submit"/>
</form>
<script type="text/javascript">
function toggleExternal() {
document.getElementById("extText").disabled = false;
var divis_el = document.getElementById("division");
for (var i = 0; i < divis_el.children.length; i++) {
divis_el.children[i].disabled = true;
}
}
function toggleDivision() {
document.getElementById("extText").disabled = true;
var val = document.getElementById("mySelect").selectedIndex;
var divis_el = document.getElementById("division");
for (var i = 0; i < divis_el.children.length; i++) {
divis_el.children[i].disabled = false;
divis_el.children[5].disabled = true;
}
}
function enableTextbox() {
var val = document.getElementById("mySelect").selectedIndex;
if (val == 0 || val == 1 ||val == 2 ||val == 3 ||val == 4) { document.getElementById("otherTxt").disabled = true}
if (val == 5) { document.getElementById("otherTxt").disabled = false; }
}
</script>
</body>
<?php
if(isset($_POST['submit'])) {
$client_type = isset($_POST ['client_type']) ? $_POST['client_type'] :null;
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
if($client_type == 'Division'){
$client_details = isset($_POST ['client_details1']) ? $_POST['client_details1'] :null;
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null; // both variables under if statement are needed to successfully update the data avoiding blank values.
} else {
$client_details = isset($_POST ['client_details2']) ? $_POST['client_details2'] :null;
}
if($client_details == 'Other') {
$client_details = isset($_POST ['client_details1']) ? $_POST['client_details1'] :null;
}
$query = "UPDATE contracts set `client_type`=?, `client_details`=? WHERE `id`= ?";
$stmt = $con->prepare($query);
$stmt->bind_param("ssi", $client_type, $client_details, $id);
$stmt->execute();
if ($stmt->errno){
echo "FAILURE!!! " . $stmt->error;
} else {
echo "<br>Updated";
}
$stmt->close();
$con->close();
}
?>
EDIT: What I meant is this.
As you can see the example picture from the link, the "Generation" values is displayed in all the textboxes under both Division and External after I updated the data because The value was taken from the drop down list.
The "Other" textbox is under division but it will only enabled to be entered after the selecting the value "Other" from the drop down list under Division.
I only wanted the the Division values displayed in the textbox only under Division and not the under External when Division radio button is chosen. And if I choose External and input data in the textbox, I only wanted the value displayed in the textbox under External only after updated.
When I select the values and not "Other" value, the value should not displayed in the text box under Division. When I select "Other" value, then the value should be displayed in 'Other' textbox but I don't want the value to also displayed in the text box under External.
The question I'm trying ask is how to make the textbox values display values separately. I don't want the same values displaying in all the dropdown list and textboxes? How do I do that? Sorry for poor explaination as English is my second language
Well it's no wonder why both are displaying the samething, their values are both just <?php echo $row['client_details']; ?>
You already have a checking variable, just not sure why you didn't use it here.
E.g.
<?php $extText = ($client_type == 'External') ? $row['client_details'] : "" ?>
<?php $divText = ($client_type == 'Division') ? $row['client_details'] : "" ?>
<input type="text" id="extText" name="client_details2" value="<?php echo extText; ?>" disabled />
Others:<input type="text" id="otherTxt" name="client_details1" value="<?php echo $divText; ?>" disabled />
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);
}
}
}
?>
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"; ?> />
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());
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>";
}