Insert Check Box from Array Value on Change in PHP - php

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

Related

if statement bug in php and html

<img id="post_like_btn_<?php echo $post_info['id']; ?>" class="post_like_btn"
<?php $like_result = data_like($dbc, $user_info['id']);
while($like_info = mysqli_fetch_assoc($like_result)){
if($post_info['id'] == $like_info['post_id'])
{ echo 'src="img/like/like_active.png"';
} else{echo 'src="img/like/like_dark.png"'}?>>
I have this code to change the icon image on the like button when the post id exists in likes table but when there are no values in the table, else statement does not work and shows no image. I tried to add '&& !== null' to if condition but it does not work either.
If there's no data in the likes tables for the user, the while loop has nothing to iterate over. That means the if condition never actually gets executed.
It's also worth noting another issue: It looks like your while loop will iterate over all results for all posts. If your user has liked other posts (besides the one being displayed) then your else clause will be executed multiple times, giving you multiple src attributes in your img tag (most or all of them referring to like_dark.png).
Ideally, what you need to do is make your database query search only for the user's likes on the ID of the post being displayed. That way you won't need a while loop at all. You just need to check if any result was found. If so, output like_active.png, otherwise output like_dark.png.
If you're not able to modify the query for some reason (or if you want to avoid multiple queries when displaying several posts on a page), your loop will need to go through each record and just set a boolean variable to true if it sees a like matching the current post ID. After the while loop, check that boolean variable in an if condition and only output the src attribute then. That way, you'll only output one src attribute, no matter how many records you've iterated over.
missing closing bracket on the while loop:
while($like_info = mysqli_fetch_assoc($like_result)){
if($post_info['id'] == $like_info['post_id'])
{ echo ' src="img/like/like_active.png"';}
else{echo ' src="img/like/like_dark.png"';}
}?>>
also since the following is common:
src="img/like/like"
you could remove that out of the if statement and just switch between the active and dark.png states.

How can I handle a GET variable when there is no data being sent

On my webpage, I have 2 options, to create a new list or to edit an existing list.
If the user wishes to create a new list, a new page with a textarea comes up.
If the user wishes to edit an existing list, the lists are displayed and the user can select a list. Upon selection of the list, the user is redirected to the new list page with the text area contents already filled in.
I have this if statement in the new list page to accept input from the edit-list page:
$items = $_GET['items'];
if ($items){
//get the stuff from the db and populate the text area
}
else {
//a new empty text area
}
The issue is that when I try reaching this page directly from the 'create new list' option, I get an error stating that items is an undefined variable.
This makes sense as the original page is not sending any data so there is nothing to get.
How can I work around this?
I can set the original page up to send a null value for items but I want to refrain from changing the original page.
Is there an option to check from where the request is coming from, or an option to activate a variable only if it can be received (usable by the GET feature)?
Use isset():
isset — Determine if a variable is set and is not NULL
if (isset($_GET['items'])){
//get the stuff from the db and populate the text area
$items = $_GET['items'];
}
#Eugen suggestion(check before assigning the variable:
$items = isset($_GET['items']) ? $_GET['items'] : null;
if($items) { // bla bla }
Firstly you must write/check
print_r($_GET)
if you want only check it you can use
if(isset($_GET["items"]){
//it have a value
}
Plus:If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
You want this. You need to check if $_GET['items'] is set, and then you can set $items to the result.
if (isset($_GET['items']) && $items = $_GET['items']){
//get the stuff from the db and populate the text area
}
else {
//a new empty text area
}

handling checkboxes in form submission with php and db updates

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
}

PHP $_POST is working but not getting value of HTML element

TL;DR version
I have a big form with hundreds of html input elements on it, I made a php array to store all the element names in it. When I run my process.php file it runs through that array using a loop and creates a new array, the key of that array is the name of each element, and the value of that array is the value of each element. I know this code works as element values for text boxes, radio buttons, and drop-down selections work fine. Checkboxes do not have the values put into the array, instead the key and value read the same thing, the name of the element. Why is $_POST giving me the NAME or ID of my checkbox, and not its value?
Full explanation /w code samples:
The problem I am having seems rather unusual to me as from my understanding it goes against how $_POST should work.
In any case I have been developing a travel insurance website for the past year and it is nearing completion. The client wants me to create a version of the form which they can view after people have submitted applications and it will get the values out of the file they select.
My problem is that $_POST is not getting the value of my checkbox elements but rather their name or id (both are identical so I cannot be sure which it is getting). $_POST is successfully getting the value of all radio, text, and drop-down elements, just not checkboxes.
I have a very large array in my process.php file as the form is quite large. What I've done is create an array which has the name of each element I wish to access. Below is a sample of the structure the array follows, it is far to large to post the entire thing here (400 plus elements on form).
$form_data = array
('trav_emer_med_insur',
'trav_emer_single',
'trav_emer_single_date_go',
'trav_emer_single_date_ba',
'trav_emer_single_days',
'trav_emer_annual',
'trav_emer_annual_date_go',
'trav_emer_annual_days',
'trav_emer_extend',
'trav_emer_extend_date_go',
'trav_emer_extend_date_ef',
'trav_emer_extend_date_ba',
'trav_emer_extend_days',
);
This is the code that runs on process.php to create the user data file, which is saved to a protected folder on the server.
// Create user output data
$out_data = array();
$count = count($form_data);
for( $i = 0; $i < $count; $i++ )
{
if(empty($_POST[$form_data[$i]])) {
$out_data[$form_data[$i]] = " ";
}
else {
$out_data[$form_data[$i]] = $_POST[$form_data[$i]];
}
}
//Set variable names for new file
$dir = "/home/imelnick/public_html/getawayinsured.ca/userdata/";
$timestamp=date("YmdGis");
$name = $out_data['txtApp1Name'];
$value = str_replace(" ", "", $name);
$item = $value . "^" . $timestamp . ".txt";
$filename = $dir . $item;
//Put data in file
//Open file for writing
$fileHandle = fopen($filename, 'w') or die("Can't open file");
//Write contents of out_data array to file
foreach ($out_data as $key => $value) {
$fileLine = $key . "\t" . $value . "\r\n";
fwrite($fileHandle, $fileLine);
}
//Close file
fclose($fileHandle);
The first block of names in the array belong to checkboxes and they follow the format of the following:
<input type="checkbox" name="trav_emer_med_insur" id="trav_emer_med_insur_if" value="YES" class="form_elements" onClick="if(this.checked){document.getElementById('trav_emer_med_options').style.display='block';}else{document.getElementById('trav_emer_med_options').style.display='none';}"/>
The onClick statement expands a div containing additional checkboxes which offer further options to the applicant.
My output data array which is created from the form data has the key of each item in the array as the name of the element, and the value of each item in the array the value of the corresponding HTML element.
Upon splitting the array and writing the $key/$value combination the expected value of $_POST[$form_data[0]] (note: $form_data[0] = trav_emer_med_insur) is the value of the above checkbox code, value="YES". However the output in the file reads as follows.
trav_emer_med_insur trav_emer_med_insur
I am quite sure that there is not a problem with the code that processes the form itself as other elements on the form have their values saved perfectly well to the file (radio buttons, text boxes, drop-downs all work). The Checkboxes do not, they refuse to $_POST the value of the HTML element, and simply keep putting out the name twice.
For example, another element in the form not listed in my array sample above named smoked_if is a radio button pair which asks if the applicant has smoked or not. Here is a sample output from a recent application.
As can be seen the desired result of my code is being performed.
smoked_if no
I am at a loss here because not only does this contradict the functionality of $_POST itself but since all other elements on the form have their values posted without issue it tells me there is a problem with checkbox elements and $_POST.
Any assistance is greatly appreciated.
I think your problem might be related to the fact that checkboxes are not posted when they are not checked.
See Post the checkboxes that are unchecked
if you need to get around this behaviour
AS long as the information is inside of the Form tags, it will be passed to the server. With that said, you need to understand that what is sent to the server is the NAME and VALUE of the items.
When you are looking at PHP, you want to submit, and then a string will look like: sample from http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_form_checkbox as well
?vehicle=car&vehicle=truck
In PHP when you post it, the idea is the same but just hidden from the unskilled eyes. To get the values of it in my example:
$vehicle= $_POST["vehicle"];
echo ''.$vehicle; //shows ARRAY
foreach( $item in $vehicle){
echo ''.$item.'\n'; //will iterate through all the vehicle and print them out
}
YOu can also say things like
if(in_array("car", $vehicle)){
echo "there exists a car\n";
}
http://php.net/manual/en/function.in-array.php
Since the checkboxes are posted only if they are checked, you need a workaround for that. I think the most usual fix is to use a hidden input with the same name as the checkbox's and usually 0 as value. And do not forget to put the hidden input before the checkbox :)
This way even if the checkbox is not checked you get the value of the hidden input. If the checkbox is selected the hidden field's value is overwritten in the POST array by the one from the checkbox.

how would I return any items in an array that do not match any $_POST results

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) . ")");
}

Categories