I am using checkboxes in my form to allow the user to turn on/off certain settings. I load the form by providing the correct 'state' from values returned from the db. They can then change these and submit the form where it is processed. Example...
<input type="checkbox" name="settings[something]" '.($settings[one] == 1 ? 'value="1" checked' : 'unchecked').'/>
<input type="checkbox" name="settings[somethingelse]" '.($settings[one] == 1 ? 'value="1" checked' : 'unchecked').'/>
... and so on...
On the receiving end is where I can't seem to come up with a good solution to handle these.
If any of these are unchecked then the value is not even sent. If it is checked then a value of '1'.
So, other than doing something like :
$something = $_POST['settings'][something']
$somethingelse = $_POST['settings'][somethingelse']
... and so on
if (!$something == 1)
{
$something = null;
}
... and so on
for each value I am expecting... is there an easier way I am missing here? I have to check each value whether it was sent or not because I am also including an option to set these values as default for multiple rows in my db - not just the one they are editing.
EDIT :
I took some time to think about this. In my database I am storing these as 1 or 0 values. Rather than checking if they were posted (set) on the receiving end of the form I am going to check if they are != to 1. I can run down the list of values and everything that is not equal to 1 is set to 0. This way I have a full list of all values to update in the db AND I am verifying the data integrity before inserting it into the database (1 or 0).
I am now trying to think of a quicker way to run through my 'list' to check rather than an if statement for each. Going to play around with some arrays and see what I can come up with.
Checkboxes are a bit special as they are not sent to the server when they are not checked.
So the best way to check for a checkbox, is not by it's value, but simply by checking if it is set:
if (isset($_POST['settings']['something']))
{
// Do what you need to do
}
else
{
// The checkbox was not on the form (you should know that already) OR unchecked
}
Related
So, I'm running this code
<td><input type="checkbox" name="bill[]" <?php if ($row['BillBack'] === '1') echo "checked"; ?>></td>
which creates a check box each time
while ($row1 = $result1->fetch_assoc()) {}
runs. So, right now it has 25 entries.
I want on submit button click, if the checkbox is checked to throw 1 into the database, and if it is not, to throw 0. Now, it seems the way to check if an array of check boxes is checked is with
foreach($_POST['bill'] as $selected){
echo $selected."</br>";
}
which, will return "on" for each one that is selected. BUT, my SQL has to look something like
"UPDATE Requests SET BillBack = '$bill' WHERE RequestID = $row['RequestID']"
so I assumed I needed to put the foreach loop inside of the while loop. But that returns 576 "on's"
Throwing an
(!isset($_POST['bill']))
into the while loop doesn't work, as it seems to be toggled if any of them are set, even though removing the ! only returns 24 "on's" (there is only one that is not toggled). so is there a way that while I still have the $row['RequestID'] to be able to check if each check box is set or not, and then throw it into my table while it is still associated with a $row?
Add the $row["requestID"] as the value of the checkbox. Then your bill[] will contain the requestID's you need.
For checkboxes, the contents of the value property do not appear in the user interface. The value property only has meaning when submitting a form. If a checkbox is in checked state when the form is submitted, the name of the checkbox is sent along with the value of the value property (if the checkbox is not checked, no information is sent).
IOW, all those unchecked checkboxes send nothing, so if only two are checked you will only have two items in your array. Without a value, determining which two is impossible.
foreach ($bill as $id) {
UPDATE Requests SET BillBack = '1' WHERE RequestID = $id;
}
And you can optimize that sql using "in" but I'm at work and don't have time
I have a few checkboxes that are stored as 0 for unchecked or 1 for checked as booleans.
I am now trying to echo back the values using laravel such as
echo $request->facebook
Which returns 1 or 0. It does not return the value of "facebook".
In my view I have:
<input type="checkbox" value="facebook" name="facebook" class="css-checkbox" />
In my model I have this:
$request->facebook = Input::has('facebook');
$request->save();
The model will check the form for the checkbox facebook and saves the boolean value in the database.
What is the best way to echo "facebook" if the checkbox was checked or echo out nothing, if the checkbox was unchecked?
This is what I do for checkboxes in my controllers:
$object = new MyObject;
$object->facebook = Input::has('facebook') ? 1 : 0;
$object->twitter = Input::has('twitter') ? 1 : 0;
$object->somethingElse = Input::has('someCheckbox') ? 1 : 0;
$object->save();
There may be better ways to do it but this is what I typically do. It's easy to read and understand and keeps your code organized.
I've experimented with moving things like this into the model using mutators, but I was kind of unsure about using the Input class on the model. In your controller POST method, the Input class is always going to be there. There is always going to be Input to check and use. But on some random model method, it's possible that you may access that method someday outside of a POST request and then there is no post input, so things like Input::has() will return false and set those values to zero.
There may be a more elegant way to do it. I'm not sure what though.
I have several input fields and I want it to submit when there is only one field with entered values and the others are empty (updating user data). I worked by now with isset() but this only sends the form when every field is filledout:
if (isset
($_POST['submit']) AND
($_POST['firstname']) AND
($_POST['lastname']) AND
($_POST['address']) AND
($_POST['ZIP']) AND
($_POST['phonenumber']) AND
($_POST['mail']) AND
($_POST['group'])
)
Later on I check in the mail template (another file) if there is a value and wheter to show it in the mail or not:
{if !empty($firstname)}{translate text='First Name'}: {$firstname|escape} {/if}
Is my idea ok or is there an easier way to solve this?
The first if statement is in conflict with your requirements; you are requiring all fields to be filled in by using the AND operation - use OR and it will work with any single field value.
Validation should/could also be performed on the page itself by using javascript as Matt recommends.
To ensure that only one field is set do the following you could count the number of entries in _POST
if(count($_POST) == 1 AND
(isset($_POST['submit']) OR
isset($_POST['firstname']) OR
isset($_POST['lastname']) OR
isset($_POST['address']) OR
isset($_POST['ZIP']) OR
isset($_POST['phonenumber']) OR
isset($_POST['mail']) OR
isset($_POST['group'])
))
Either way it's not a very elegant way of doing this - but it will work.
If you want only one value from a field which is set to required (if possible, use javascript, or HTML5 has a required attribute for that), simply ignore other values from other fields:
<?php
if ( isset( $_POST['submit'] ) ) {
$wanted_value = addslashes( strip_tags( $_POST['input_name'] ) );
// preventing from sql injection
// ignore other values
// and start manipulating it
}
?>
One suggestion would to be to use javascript and your onSubmit function on the form in addition to a serverside check. Using that, you can check all of your fields, and alert the user to fill some in BEFORE it gets submitted to the server.
In a javascript function check all of your inputs for a correct input, and allow the data to be sent to the server if it is all filled in correctly, or pop up an alert saying what else needs to be done before it can be submitted.
Doing this check strictly serverside will require a server request to check the input every time, as opposed to having the client check it, and submit it only if everything is correct.
Assuming you want to send the form if there's at least one field that's filled, you could use the following if-statement:
if(count($_POST) > 1)
This allows you to submit the form and have at least one field filled, but you can also have more fields filled.
If you want to send the form only if there's one field that's filled, you could change the above if-statement to the following:
if(count($_POST) == 2)
This allows you to have only one field filled.
The reason I use "== 2" is because the submit-button is also something that will be sent.
If you want to allow all the fields to be empty, you can use the following if-statement:
if(count($_POST) > 0)
This would allow you to submit the button and leave all the other fields empty.
The reason this works is because $_POST is a pre-defined array-variable.
To ensure that the user only uses fields that you want them to use and still keep the code clean, you can use an array.
Do the following:
$allowed_fields = array('firstname','lastname','address','ZIP','phonenumber','mail','group');
And then just add the following to your if-statement:
if(count($_POST) == 2 AND in_array($allowed_fields, $_POST))
I have a page with two forms on it (and two submit buttons), and the forms link the page back to itself with action="" for the INSERT INTO statements. One of the INSERT INTO statements is:
<?php
$sql="INSERT INTO panelProduct (length_mm, width_mm, aperture)
VALUES ('$_POST[p_length_mm]','$_POST[p_width_mm]','$_POST[p_aperture]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
One of the reasons I have put the form and the INSERT statements on the same page is that the form allows users to add products to an order, and there may be several products (so I thought the user could keep submitting until they're done...). The other reason was that I need to use a $_POST value sent from the previous page to do something else with the products they enter, and I don't know how to send it to more than one page.
Anyway, the problem I have found is that a new row is inserted into the database every time the page is refreshed, containing NULL values. This makes sense to me as the PHP will execute the statement above every time it encounters it. My question therefore is how I can make some sort of condition that will only execute the INSERT statement if the user enters something in the form and 'Submits'?
you could use the empty() method of PHP to check for null values in each of the variables.
Something like:
if(!empty($_POST['p_length_mm']) && !empty($_POST['p_width_mm']) && !empty($_POST['p_aperture']))
{
//execute your query here
}
else
{
//if there's an alternative you would like to happen if values are null, or just leave out.
}
Hope that does the trick.
You have to check if data come from your form. I'd suggest this approach - name your submit button (i.e. <input type="submit" name="my_submit_button" value="Whatever" /> and this condition to your insert code:
if( isset( $_POST['my_submit_button']) ) {
.. process your post data
}
Also, always remember not to trust user provided data. Verify if all data expected are present in$_POST and format matches requirements (i.e. you ask for number and received letters etc). If all test passed, then you are ready to commit your data to DB.
You need a condition like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) {
// a form was posted
}
Of course, you still need to check whether your post actually contains the right stuff:
isset($_POST['p_length_mm'], $_POST['p_width_mm'], $_POST['p_aperture'])
Even better is to use filter_input_array() to sanitize your incoming data; your current code is open to SQL injection attacks. Using PDO or mysqli and prepared statements is the way to go.
I am writing a PHP/MySQL application that maintains a masterlist of user preferences and I've gotten myself stuck trying to remove items from that list. Currently the application generates a list of items and marks a checkbox next to the ones a user has previously selected, the user can then change their selections (either adding or removing checkmarks) and resubmit. The form only submits supplyid's for items the user has checked.
I have the list sorted so that unmarked selections are shown first and I've got the code to insert/update items in the database working, but I'm having problems figuring out how to delete the items the user has unchecked (and which now do not return supplyid's).
At this point, I've written a MySQL query to return only results that were previously included on the list (as those are the only ones which could need to be removed.) What I need are the items in the array returned by the query that do not match any $_POST results. I've been successfully comparing the array to the $_POST results of items previously included, but I can see my logic is wrong in the part where I'm trying to get back the results which don't match. While I'm able to view which items match, I'm not sure how to eliminate them as possibilities. Am I going about this in the wrong way entirely?
$iduser = $_SESSION["iduser"];
$possibleresults = $_POST["possibleresults"];
$sql_onlist = "select supply.idsupply from supply, kit
where supply.class = 'basic'
and kit.iduser = '".$iduser."'
and supply.idsupply = kit.idsupply";
$possible_delete = $connection->query($sql_onlist);
//for each record we know is already in the database, check to make sure it has been checked, otherwise delete
for ($i=0; $i<$possibleresults; $i++) {
$count = 0;
$item_delete = $possible_delete->fetch_assoc();
if ($_POST['item_'.$i.'']) {
$idsupply = $connection->real_escape_string($_POST['item_'.$i.'']);
//if there is a match, increase the counter
if ($idsupply == $item_delete["idsupply"]) {
$count++;
//this does successfully return a count = 1 - idsupply = number for all rows which should have matches
echo "count = ". $count . " - idsupply = " . $idsupply;
}
//this statement doesn't work because it doesn't know which idsupply
if ($count < 1) {
$idsupply = $item_delete["idsupply"];
$sql_delete = "delete from kit
where idsupply = '".$idsupply."'
and iduser = '".$iduser."'";
$result_delete = $connection->query($sql_delete);
}
}
There are a couple different solutions to this problem; here's a few strategies I've used before.
-- Delete all the entries every time you update a user's preferences
Not terribly efficient, but it's easy to implement. Every time they save their preferences, first set all the values in the database to whatever the 'unchecked' value is. Then, save their preferences as normal.
-- Give unchecked boxes a value
If you put a hidden input element right before a checkbox and give it the same name as the checkbox, the hidden element will submit its value whenever the checkbox is not checked. E.g.,
<input type='hidden' name='box1' value='off' />
<input type='checkbox' name='box1' value='on' />
This will let you know which IDs to unset in the database.
There may be a more database-oriented solution as well, but I'd have to know more about your structure to suggest anything.
Holy moly, what a tangled mess... kinda painted yourself into a corner eh? No worries it happens to all of us. :)
So I think that once you have a truly working algorithm the code just kinda comes together around it. So lets analyze your problem:
Your main objective is to store a users settings.
You are using a form and checkboxes to both display the current settings and to allow the user to change their current settings. This is graceful enough.
Generate a list of the users POSTed settings (aka get the new settings from the POST array) and store those results in a dedicated data container like an array or a linked list.
Once you have a list of new settings, you need to use that list as a map to set/unset various fields within a database table.
Get a list of ALL of the users saved settings from the database storing that in a different data container
Do a case by case comparison, seeing if the variables match, record the results in yet another data container, or do an immediate write to the database.
Present the user with a human readable result of their operation.
NOTE: Incidentally, you probably already know this, but if you use isset($_POST['mychkbox1']) and it returns a positive value, then that checkbox was checked. If isset() returns false, the checkbox was not set, or does not exist. Like I said you probably already knew that, but I figured I toss it in there.
Good luck
h
I didn't quite understand your code, but I think you need something like this
$to_keep = array();
for ( $i=1 ; $i < 10 ; $i++ ) {
// Add ids of elements we want to save
$to_keep[] = $i;
}
if ($to_keep) {
mysql_query("DELETE FROM table WHERE id NOT IN (". implode(',', $to_delete) . ")");
}