mysql Update Statement depending on number of checkbox checked - php

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)));

Related

Query building depending checkboxes selection [duplicate]

This question already has an answer here:
Building an SQL query based on checkboxes
(1 answer)
Closed 8 years ago.
I want to build a query form my database depending my checkboxes list.
My checkboxes:
<input type="checkbox" id="searchName" checked> Name
<input type="checkbox" id="searchAddress"> Address
<input type="checkbox" id="searchCompany"> Company
<input type="checkbox" id="searchComments"> Comments
My PHP:
$subQuery='';
if($_POST['searchName']=='true') { $subQuery .= " AND KDX_Name LIKE :KDX_SearchTerm"; }
if($_POST['searchAddress']=='true') { $subQuery .= " OR KDX_PostalAddress LIKE :KDX_SearchTerm"; }
if($_POST['searchCompany']=='true') { $subQuery .= " OR KDX_Company LIKE :KDX_SearchTerm"; }
if($_POST['searchComments']=='true') { $subQuery .= " OR KDX_Comments LIKE :KDX_SearchTerm"; }
My problem:
If the first checkbox is not checked, my query is not working cause it works with OR whereas it must start with AND.
Could you please help ?
Thanks.
You have many mistakes in your code in HTML and in PHP ...
I'll not mention everything here, but this is how I would do this.
<input type="checkbox" name="searchName" checked="checked" />Name
<input type="checkbox" name="searchAddress" />Address
<input type="checkbox" name="searchCompany" />Company
<input type="checkbox" name="searchComments" />Comments
<?php
$fields = array(
'searchName' => 'KDX_Name',
'searchAddress' => 'KDX_PostalAddress',
'searchCompany' => 'KDX_Company',
'searchComments'=> 'KDX_Comments',
);
$cond = array();
foreach ($fields as $form_field => $db_field) {
if (isset($_POST[$form_field])) {
$cond[] = "$db_field LIKE '%'" . mysql_escape($_POST[$form_field]) . "%'";
}
}
$subQuery = implode(' OR ', $cond);
?>
More important are these things:
correct HTML form (not id, but name),
easy to extend PHP (use array for field names),
don't check for $_POST[foo]=='true' which is absolutely wrong,
add conditions in array and at the end use implode to easily concatenate everything together,
escape user input variables to avoid SQL injection attacks.

PHP - Build PDO Query Parameters from multiple checkbox form

I am trying to build a PHP PDO query, based from a set of checkboxes that a user has selected on the previous page.
So i have the following checkboxes in my form:
<input type="checkbox" name="websites[]" value="one" id="one">
<input type="checkbox" name="websites[]" value="two" id="two">
<input type="checkbox" name="websites[]" value="three" id="three">
Once submitted i then want to build a pdo query and query parameters based from what checkboxes the user selected - they have to all be in the one query though. I know that any checked boxes will be stored in my $_POST['website'] array but how can i then take that and put them in the query? For example say the user selected one and three only, i then want to only select those fields from my database table:
$results = $_POST['websites'];
$query = "
SELECT
one,
three
FROM
table
";
How can i do the above?
First of all you should use a white-list of allowed fields to avoid sql injection. Then you need to check every sent-in entry to see if it exists in your white-list and add it to the query if it does.
So something like:
$allowed_fields = array(...);
$fields = array();
// only checked fields are sent to the server
foreach ($_POST['websites'] as $value)
{
if (in_array($value, $allowed_fields))
{
$fields[] = $value;
}
}
$query = 'SELECT `' . implode('`, `', $fields) . '` FROM table';

How to select values on mysql database for each value from checkbox array

I'm trying to make a bulk action.
I have checkboxes,
<input type="checkbox" name="check_id[]" value="1">
<input type="checkbox" name="check_id[]" value="2">
<input type="checkbox" name="check_id[]" value="3">
I wanted to select values from mysql table for each selected checkboxes then use my function to delete data based on the fetched values. I tried,
for( $i = 0; $i < count( $_POST['check_id'] ); $i++ ) {
$manufacturers_id = prepare_input($_POST['check_id'][$i]);
$manufacturer_query = mysql_query("select manufacturers_image from " . TABLE_MANUFACTURERS . " where manufacturers_id = '" . (int)$manufacturers_id . "'");
$manufacturer = mysql_fetch_array($manufacturer_query);
delete_image(DIR_IMAGES . $manufacturer['manufacturers_image']);
}
The problem is that, there is no fetched mysql values based on $_POST['check_id'] even though im sure that i have manufacturers_image where is manufacturers_id is either 1,2 or 3.
Is there a correct way to accomplish this?
Change this line
$manufacturer = mysql_fetch_array($manufacturer_query);
to
$manufacturer = mysql_fetch_assoc($manufacturer_query);
It is returning an array ... you use while() or you fetch first image
delete_image(DIR_IMAGES . $manufacturer[0]['manufacturers_image']);

Multiple Checkbox Update Query

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);
}
}
?>

PHP form checkbox and undefined index

I am getting an "Undefined index" error when submitting a form with an un-checked checkbox. Is there any other way besides running an "isset" or "empty" check on each individual posted value?
I have looked at this Question and am having trouble believing that this is the only solution.
Below is some example code:
EDIT: please not that these are not the actual names of the tables columns; they are named uniquely (like "postAddress, displayPhone, student, etc.)
You could write a function that checks whether a checkbox was checked:
function checkbox_value($name) {
return (isset($_POST[$name]) ? 1 : 0);
}
Now call that function in your query like this:
$sql = 'UPDATE table SET '.
'checkbox1 = '. checkbox_value('checkbox1') .','.
'checkbox2 = '. checkbox_value('checkbox2') .','.
'checkbox3 = '. checkbox_value('checkbox3') .','.
'checkbox4 = '. checkbox_value('checkbox4') .','.
'checkbox5 = '. checkbox_value('checkbox5') .','. "LIMIT 1";
If you want a on/off checkbox you can write a hidden value before you write the checkbox.
<input type="hidden" name="checkbox1" value="no" />
<input type="checkbox" name="checkbox1" value="yes" />
This will always return a value, either no (default unless checkbox is checked by default) or yes.
You can validate input with the filter functions with FILTER_VALIDATE_BOOLEAN.
Its easier if you write a function for this, like formCheckbox($name), with options for values (value 'on' means checkbox is checked by default), attributes, etc.
try the following
<?php
//first part of the query
$query = "UPDATE table SET ";
$howManyCheckboxes = 5;
//for every checkbox , see if it exist , if it is, add it to the query
for($i=1;$i<=$howManyCheckboxes;$i++)
{
if(isset($_POST['checkbox'.$i]))
{
$query = $query . " checkbox".$i."='".escape($_POST['checkbox'.$i])."',";
}
}
//lets remove the last coma
$query = substr($query,0,-1);
//add the rest of the query
$query = $query . " LIMIT 1";
$result = mysql_query( $query );
if( ! $result ) echo "um, not everything went as expected.";
?>

Categories