Multiple Checkbox Update Query - php

I have an application with multiple values from a database table that I generate alongside individual checkboxes. The checkboxes are given a value associated from the database of course.
Now what I am wanting to do is on submit update the database given the values checked or unchecked. This would be simple if I had hardcoded the values in HTML, but since the values are database driven I am not sure how I would go about doing this.
Quite simply: I want to update database given checkbox values are checked or not.

The title of your question says "radio" buttons, but your question asks about "checkboxes". They are very different things. Here's an example.
<input type="radio" name="fish" value="one"> One Fish
<input type="radio" name="fish" value="two"> Two Fish
<input type="radio" name="fish" value="red"> Red Fish
<input type="radio" name="fish" value="blue"> Blue Fish
The above is an example of a radio button input array. It contains one field name ("fish") and four possible values ("one", "two", "red", "blue").
Since it's a radio button, only one of those choices can be valid at any given time. That means that you either get "one" OR "two" OR "red" OR "blue", but it's not possible to select both "one" and "red" at the same time, unless the field names are different ("number", "color", for example).
Checkboxes are binary, like a light switch. They are either on or off. Each checkbox represents its own field name.
<input type="checkbox" name="light"> On
<input type="checkbox" name="status"> Single?
<input type="checkbox" name="featured"> Featured
You may check as many of these as you wish, given that each has its own individual field name that can either be true or false (on or off).
Since I don't know which one you're talking about, I'll give quick examples with each.
First, the radio example:
<? $types = array("one","two","three","four"); ?>
<? foreach ($types as $type): ?>
<input type="radio" name="fish" value="<?= $type ?>"/> <?= ucwords($type) ?> Fish
<? endforeach ?>
When the form is submitted, you will wind up with a response similar to this:
Array
(
[fish] => "one"
)
Assuming "one" was selected in the radio button array.
Now, the checkbox example:
<? $fields = array("light", "status", "featured"); ?>
<? foreach ($fields as $field): ?>
<input type="checkbox" name="<?= $field ?>"/> <?= ucwords($field) ?>
<? endforeach ?>
This provides the same HTML input as my HTML-based example above. If you check a field and submit the form, the result would look like this:
Array
(
[light] => "on"
[status] =>
[featured] => "on"
)
Where "on" is if the checkbox is checked and blank (or possibly "off") if the checkbox was not checked.
Depending on which one, you will need to insert these values into the database by taking these responses and parsing them, then creating a SQL query.
With the radio button, the variable would be simple:
$fish = $_POST['fish'];
$sql = 'INSERT INTO fishes (fish) VALUES ('.mysql_real_escape_string($fish).')';
mysql_query($sql);
With the checkbox, it would be a little more difficult:
$light = $_POST['light'] == 'on' ? 1 : 0;
$status = $_POST['status'] == 'on' ? 1 : 0;
$featured = $_POST['status'] == 'on' ? 1 : 0;
$sql = "INSERT INTO checkboxes (light, status, featured) VALUES ($light, $status, $featured)";
mysql_query($sql);
As you mentioned, your question was rather vague. I hope my answer provides enough information to get you started in the direction you need to go. This is a super basic example, of course, and you would likely want to generate the SQL statements dynamically so that you don't have to hard code every field or apply this to a more generic function to handle multiple types of forms.
Anyway, good luck. Hope this helps.

For those who are wondering how I accomplished this, here is my code:
$publish = $_POST['publish'];
while (list ($key,$val) = #each ($publish))
{
$temp=mysql_query("SELECT * FROM temp WHERE id = '$val'");
while($row = mysql_fetch_array($temp))
{
$id = $row['id'];
$title = $row['title'];
$maintext = $row['maintext'];
$order = $row['order'];
$pageID = $row['pageID'];
$sql = "INSERT INTO content (id, title, maintext, order, pageID) VALUES ({$row['id']}, {$row['title']}, {$row['maintext']}, {$row['order']}, {$row['pageID']})";
$sql2 = "UPDATE content SET `title` = '$title', `maintext` = '$maintext', `order` = '$order', `pageID` = '$pageID' WHERE `id` = '$id'";
$sql3 = "DELETE FROM temp WHERE id = '$id'";
mysql_query($sql);
mysql_query($sql2);
mysql_query($sql3);
}
}
?>

Related

mysql Update Statement depending on number of checkbox checked

Problem statement:
I have a form with multiple checkbox Fields, i have validated it so
user can select maximum 9 checkbox and atleast 1 with jquery.
I collect the Form checked values using Post method.
i have mysql table with 12 columns.
first 3 columns are "id", "rollnum", "selectStatus"
Through session variables created during Login, i get roll number of student. So i can Run Update Query on particular row.
Question: How do i Update those 9 subject columns according to user checked inputs. Note : i stored those checked input field values in an array.
Code
<form action="index.php" id="form-3" method="post">
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="ucs303">UCS303 Operating Systems
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="ucs406">UCS406 Data Structures and Algorithms
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec401">UEC401 Analog Communication Systems
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec612">UEC612 Digital System Design
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec307">UEC307 Electromagnetic Field Theory & Trans Lines
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec502">UEC502 Digital Signal Processing
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec510">UEC510 Computer Architecture
<button type="submit" name="year-3-submit">Submit Selection</button>
</form>
<?php
if(isset($_POST['year-3-submit'])){
if(!empty($_POST['year-3-checkbox'])){
$subjectCheckList = array();
$subjectCheckList = $_POST['year-3-checkbox'];
}
}
?>
It depends on user how many checkbox is selected.
I donot know how to write UPDATE sql query which updates values of number of columns == size of array.
for example:
User 1 has selected 3 checkbox and submitted form, we have array of size 3 and UPDATE 3 columns of table.
User 1 has selected 6 checkbox and submitted form, we have array of size 6 and UPDATE 6 columns of table.
I donot want to write 9 switch case statements for all possible sizes
of array. Any idea? please?
Based on OP's comments, you can make the code generic as follows:
// Check if atleast one subject has been selected
$selectedSubjects = array_filter($subjectCheckList);
// If no subject selected
if (empty($selectedSubjects)) {
$sql = "UPDATE subjectmaster
SET substatus = 0
WHERE rollno = '" . mysqli_real_escape_string($rollnumber) . "'";
} else {
// Initialize the sql string
$sql = "UPDATE subjectmaster
SET substatus = 1 ";
$i = 1;
foreach ($subjectCheckList as $subject) {
$sql .= ", sub" . $i . " = '" . mysqli_real_escape_string($subject) . "' ";
}
$sql .= " WHERE rollno = '" . mysqli_real_escape_string($rollnumber) . "'";
}
Also, note the use of mysqli_real_escape_string. It helps in preventing SQL injection. For better ways to prevent SQL injection, you may check How can I prevent SQL injection in PHP?
Well, 1st of all it is not clear what should be the default valued for each column.
Since your MySQL columns are set by numbers (sub1, sub2, etc) then your form should represent them accordingly, with the proper value. for example:
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="1">
This way, you can loop easily and update the table (I assume the sub columns are TINYINT(1) DEFAULT NULL) :
<?php
if(isset($_POST['year-3-submit'])){
if(!empty($_POST['year-3-checkbox'])){
$subjectCheckList = array();
$query = "UPDATE table SET ";
foreach ($_POST['year-3-checkbox'] as $key => $value) {
$query .= " sub" . $value . " = 1, "
}
$query = substr($query, 0, -1);
}
}
?>
Hope this helps
Guy
You can also use array_filter, array_combine and array_slice.
<?php
$subs = [':sub1',
':sub2',
':sub3',
':sub4',
':sub5',
':sub6',
':sub7',
':sub8',
':sub9'
];
// use $dataFromForm = array_filter($_POST['year-3-checkbox'])
$dataFromForm = ['11111',
'222222',
'3333333'];
$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '*******');
$sql = 'UPDATE test SET sub1 = :sub1, sub2 = :sub2, sub3 = :sub3, sub4 = :sub4, sub5 = :sub5, sub6 = :sub6, sub7 = :sub7, sub8 = :sub8, sub9 = :sub9';
$sth = $dbh->prepare($sql);
$sth->execute(array_combine(array_slice($subs, 0, count($dataFromForm), $dataFromForm)));

how do you store multiple rows and column array in mysql

I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}

How to retrieve imploded array from a cell in an MySQL database through PHP

Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.

How to work with checkboxes in relation to database?

Hi I am trying to build a form with checkboxes and upon submitting the form, I want to see which checkboxes were checked and update the database accordingly. How is this done? I've tried so many different code and none of them worked. The closest I've gotten was to update only the checked ones. I also need to update the database if they are unchecked as well like a toggle.
So far my code is like this for the form
<form action="" method="post">
<input type=checkbox" value="<?php echo member['id']; ?>" name="member[]" />
<input type="submit" name="update" value="Update" />
</form>
And for the PHP loop I have (excerpt)
foreach ((array)$_POST['test'] as $member) :
$sql = "UPDATE `sp_members` SET `allow_test` = '1' WHERE `id` = '$member'";
Since I think the loop only picks up the checkboxes that are checked, it doesn't pick up the ones that were orignally checked and now unchecked...
Any help appreciated!
Simply update everything instead of trying to figure out what changed - if you programmed it yourself, you would have to make your code a lot more complicated, and as the database is already optimized for speed, it's better to just stuff it in the DB and let it handle it.
You could use a ternary operator to set the correct value.
$sql = "UPDATE `sp_members` SET `allow_test` = '"
. ( $_REQUEST['checkbox'] ? 1 : 0 )
. "' WHERE `id` = '" . mysql_real_escape_string( $member ) . "'";
It checks $_REQUEST['checkbox'] for a non-null, non-zero string and if true, returns 1, if false, returns 0.
(($_post['member']) ?$allow_test = 1 : $allow_test = 0;
$sql = "UPDATE `sp_members` SET `allow_test` = $allow_test WHERE `id` = '$member'";
The reason why this hasn't been working (and won't in the already provided answers) is because checkboxes that are not checked won't exist in the $_POST/$_REQUEST arrays. The other side of that is if they do exist, they must be true.
When you're doing the check to see what the value is, you are causing an error because the key to the array doesn't exist.
Instead, you need to know the available checkboxes and then check if each isset() in the array.
Webform:
<form action="foo.php" method="post">
<input type="checkbox" value="<?php echo $value1; ?>" name="checkbox1" />
<input type="checkbox" value="<?php echo $value2; ?>" name="checkbox2" />
<input type="submit" name="update" value="Update" />
</form>
PHP:
$checkboxes = array(
'column1' => 'checkbox1',
'column2' => 'checkbox2',
);
foreach ($checkboxes as $column => $checkbox)
{
$value = (isset($_POST[$checkbox]) ? 1 : 0);
$sql = "UPDATE `table` SET `$column` = '$value' WHERE `id` = '$member'";
}
When confronted with this, I usually punt and rely on a transaction to update this stuff for me. As you've discovered, unchecked checkboxes won't get submitted with the form, so you'd have to do tedious comparisons to figure out what's changed each time and build up an appropriate update and/or delete query sequence.
Instead, I fire up a transaction, delete all the old checkbox values stored in the DB, and then insert the new ones submitted with this request. Unless you've got the checkboxes acting as foreign keys and/or triggers set on them at the DB level, this is a relatively lightweight option and saves you the trouble of having to compare the old and new lists for changes.

How to check a check box if it's value is in DATABASE. PHP

I have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.

Categories