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.
Related
I have written a code to save the check values of checkboxes to database.
check condition is working fine as in the checked values are saving to database when submit and it keeps checked when submit and refresh.
But when it uncheck and submit then refresh the page the checkbox still keeps remained checked. It won't saved the status of unchecked.
I include a chunk code which is related to this issue. If anyone can get the issue that'd be great.
echo "<form action='' class='' method='post'><tr>";
$sql_stamp = "SELECT check_list FROM time_stamps WHERE nJobNumber=".$nJobNumber;
$query_stamp = $conn->prepare($sql_stamp);
$query_stamp->execute();
$numRows = $query_stamp->rowCount();
if($numRows > 0){
$row_stamp = $query_stamp->fetch(PDO::FETCH_ASSOC);
$checkboxes = explode(',',$row_stamp['check_list']);
echo ' <td><center> <input type="checkbox" name="check_list[]" value="shop_drawing" '.(in_array( "shop_drawing",$checkboxes) ? "checked=checked" : "").'></td>';
echo ' <td><center><input type="checkbox" name="check_list[]" value="site_measure" '.(in_array( "site_measure",$checkboxes) ? "checked=checked" : "").'></td>';
echo ' <td><center><input type="checkbox" name="check_list[]" value="shop_drawings_approved" '.(in_array( "shop_drawings_approved",$checkboxes) ? "checked =checked" : "").'></td>';
echo '<td><center> <input type="checkbox" name="check_list[]" id="check" value="batch" '.(in_array( "batch",$checkboxes) ? "checked=checked" : "").'></td>';
echo '<td><center> <input type="text" name="batch_no"><br> </td>';
echo ' <td><center> <input type="submit" name="submit" value="Submit"/> </td>';
echo '<td><input type="hidden" name="job_number[result]" value="'."true".'"</td>';
echo '<td><input type="hidden" name="job_number[number]" value="'.$nJobNumber.'"</td>';
}else{
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="shop_drawing"></td>';
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="site_measure"></td>';
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="shop_drawings_approved"> </td>';
echo '<td><center> <input type="checkbox" name="check_list[]" id="check" value="batch"></td>';
echo '<td><center> <input type="text" name="batch_no"><br> </td>';
echo "<td><center> <input type='submit' name='submit' value='submit'></td>";
echo '<td><input type="hidden" name="job_number[result]" value="'."false".'"</td>';
echo '<td><input type="hidden" name="job_number[number]" value="'.$nJobNumber.'"</td>';
}
echo "</tr> </form>";
}
echo "</tbody> </table>";
?>
Insert values to database:
if(isset($_POST['submit']))
{
$checkbox = $_POST["check_list"];
$job_number = $_POST["job_number"];
$batch_no = $_POST["batch_no"];
date_default_timezone_set('Australia');
$date_time = date("Y-m-d h:i:sa");
//$username = "$SESSION[userid]";
if($job_number["result"] == "true"){
if(!empty($_POST['check_list']))
{
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
}
}
else{
if(!empty($_POST['check_list']))
{
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('INSERT INTO time_stamps (nJobNumber,time_date,username,batch_no,check_list) VALUES (?,?,?,?,?)');
$stmt->bind_param('issss',$job_number["number"],$date_time,$username,$batch_no,$checkboxes);
$stmt->execute();
}
}
}
Basically, What's my requirement is when a user uncheck a 'checked' checkbox it should be unchecked when submit the form (after a refresh). But in my case it keeps checked.
Neither of your queries will execute if the user submits a form with no checkboxes checked. While this may be ok for your INSERT query, it will not allow the check_list field to be updated. So you will need to change the code for updates from this:
if(!empty($_POST['check_list'])) {
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
}
to this:
$checkboxes = empty($_POST['check_list']) ? '' : implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
You may also want to change the insert code in the same way if you want to insert a record even when the user doesn't check any checkboxes.
Thanks to #Phil for his input.
I think I see a couple of problems. I see this line:
$job_number = $_POST["job_number"];
But then I see you use this:
if($job_number["result"] == "true"){
So I ask, is $job_number an array or just a string/value?
Also, unchecked checkboxes don't submit a value. And since you test for a not empty $_POST['check_list'] value your UPDATE will never run. Remove the ! character.
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 want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}
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 "hidden" input before the checkbox, but the only problem is that it is not working. When I click on it, it resets all checkboxes to 0.
I think you are missing how the combo checkbox + hidden input does work.
So here you go freely inspired by this answer:
<input id="foo" name="foo" type="checkbox" value="1" />
<input name="foo" type="hidden" value="0" />
Looks like you do know, if you use the trick, that, if the checkbox is unchecked, it will not be present in the post. So to trick the form, we will always add an hidden field. And if the checkbox is checked, then the fact that it will be included in the post is going to override the value of the hidden input.
So for your specific problem :
<td>
<input type="checkbox" value="1" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]" <?php echo ($room->trained == 1) ? ' checked' : '' ?> /> Trained
<input type="hidden" value="0" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]"/>
</td>
Please note the use of the ternary operator on this part of the code <?php echo ($room->trained == 1) ? ' checked' : '' ?> which I may use a lot when writing html template.
Please also note the trick on the name trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>] which is needed because we cannot set the user_id as value of the input.
Then for the processing part :
if ( isset ( $_POST['submit'] ) ) {
foreach ( $_POST['trained'] as $ids => $value ) {
// This query needs protection from SQL Injection!
// ^ good point, on which I would suggest you using PDO and prepared statement :)
list($room_id,$user_id) = explode('_',$ids);
// ^ now need to explode the name on the underscore to get both user_id and room_id cf the trick above
$untrainQuery = "UPDATE room_users SET trained = '$value' WHERE user_id = $user_id AND room_id = $room_id";
$db->update ( $untrainQuery );
}
}
Wash, rinse, repeat for every checkbox you need and you should be good to go.
my code works as expected but a little issue occurred, i try retrieving values from checkboxes with same name and hidden fields with the same name, it works but one of the hidden field keeps on returning the first value even if the checkbox was not selected.
here is my code
while($row=mysql_fetch_array($res1)){
?>
<tr><td class='bold'><?php echo $sn;?><input type="hidden" name="snum[]" value="<?php echo $sn; ?>" /></td>
<td><?php echo $row['subLocationName']; ?>
<input type="hidden" name="location[]" value="<?php echo $row['dllink_id']; ?>"/></td>
<td><input type="checkbox" name="available[]" value="<?php echo $row['subLocationName']; ?>"/></td>
<input type="hidden" name="locationID[]" value="<?php echo $row['locationName']; ?>"/>
<input type="hidden" name="sublocation[]" value="<?php echo $row['subLocationName']; ?>"/>
<input type="hidden" name="device[]" value="<?php echo $row['deviceName']; ?>"/>
<td></td><td></td></tr>
<?php
$sn++;
}
the values are from my database.
the retrieving code is this
if(isset($_POST['submit_btn'])){
$serial_num = $_POST['snum'];
$locationDeviceLink = $_POST['location'];
$linkAvailable =$_POST['available'];
$location = $_POST['locationID'];
$subLocation = $_POST['sublocation'];
$device = $_POST['device'];
$measure_date = date("Y-m-d");
$sn = count($linkAvailable);
for ($i=0; $i<$sn; $i++ ){
if(!empty($linkAvailable[$i])){
echo "serial number:".$serial_num[$i]." location:".$locationDeviceLink[$i]." available:".$linkAvailable[$i]." Location:".$location[$i]." subLocation:".$subLocation[$i]." Device:".$device[$i]." Date:".$measure_date."<br/>";
}
}
}
the problem is the subLocation value, it keeps returning the first value then the second as it appears even if the associated checkbox is not checked and another checkbox is checked, please can anyone help me out, cant't think of anything more.
thanks in advance
joseph O
Rather then testing for !empty try using php's function isset.
for ($i=0; $i<$sn; $i++ ){
if(isset($linkAvailable[$i])) {
echo "serial number:".$serial_num[$i]." location:".$locationDeviceLink[$i]." available:".$linkAvailable[$i]." Location:".$location[$i]." subLocation:".$subLocation[$i]." Device:".$device[$i]." Date:".$measure_date."<br/>";
}
}