Checkbox "checked" value conflict with session and DB values PHP - php

I've been trying for a few days to figure this out but can't get it to work out correctly as I run through testing the scenarios. Basically, this is on an edit form, so it's pulling the stored value from the database. I have it save as either "1" or "0", 1 being checked. It's also a single checkbox, not an array.
I'm trying to figure out how to make the session correctly store the choice of my checkbox so that if there's an error on the page, etc, it shows my session value correctly, but what happens is that the DB value usually ends up trumping that.
So how can I initially first display the DB value, but then display the session value if changed?
Here's what I've been playing with.
if(isset($_SESSION["include_due_date"])) {
$include_due_date = 'checked="checked"';
} else {
if((!isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 1 ) {
$include_due_date = 'checked="checked"';
} elseif((isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 0 ) {
$include_due_date = 'checked="checked"';
} elseif((!isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 0 ) {
$include_due_date = '';
}
}
Any ideas?
ADDITIONAL METHOD:
<input type="checkbox" value="1" <?php echo (isset($_SESSION['include_due_date'])?' checked="checked"' : (!isset($_SESSION['include_due_date'])) && $resInvoice[0]['include_due_date'] == 1?' checked="checked"' : ''); ?> name="include_due_date" id="include_due_date" />

So how can I initially first display the DB value, but then display
the session value if changed?
session_start(); // (Be sure to use session_start)
// If the include_due_date was set by the session
if(isset($_SESSION["include_due_date"])) {
// Set the value of $checked to the value of the session variable
// In this way, the value of the session variable takes precedence over that in the database
$checked = ($_SESSION["include_due_date"] === true);
} else {
// The session variable wasn't set, so use the value from the database to set both the checked value and the session variable.
// The next request will use the value from the session variable
if($resInvoice[0]["include_due_date"] == 1 ) {
$_SESSION["include_due_date"] = $checked = true;
} else {
$_SESSION["include_due_date"] = $checked = false;
}
}
HTML
<input type="checkbox" value="1" <?php if ($checked) echo 'checked="checked"; ?> name="include_due_date" id="include_due_date" />

Related

$_SESSION variable getting lost somewhere........or PHP ignoring "IF...ELSEIF"

I am having a problem with getting my PHP script to correctly read and execute my "IF.....ELSEIF" conditions.
In my first file, I have the following code :
if(isset($_POST['submit']) {
$selected_radio = $_POST['selection'];
$_SESSION['my_selection'] = $_POST['selection'];
if (($selected_radio == '25') {
header("url=http://xxxxxxxxxxxxxxxxx");
}
elseif (($selected_radio == '50') {
header("url=http://xxxxxxxxxxxxxxxxx");
}
}
That was the easy part.
If either "radio button" is selected, I have a Javascript function which opens a "new (child) window"
That's also easy.
But, then, comes the hard part : within that new window, the user has to select from another choice of radio buttons :
if(isset($_POST['submit']) {
$selected_radio = $_POST['my_response'];
if (($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] = '25'))
{
echo '<script type="text/javascript">window.opener.location =
"/PHP/25.php";setTimeout("window.close();", 1000);</script>';
}
elseif (($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] =
'50')) {
echo '<script type="text/javascript">window.opener.location =
"/PHP/50.php";setTimeout("window.close();", 1000);</script>';
}
Basically, this means : if the user selects "yes" in the current (child) window, then the window closes, and the parent window re-directs to "25.php" or "50.php"..........depending on the value of the $_SESSION['my_selection'] --- which was selected earlier in the parent-window
But, for some reason, it's not working. My code is executing only the FIRST IF-condition :
if (($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] = '25'))
{
echo '<script type="text/javascript">window.opener.location =
"/PHP/25.php";setTimeout("window.close();", 1000);</script>';
}
It is completely ignoring the second one.............even if the user had earlier selected "50" in the parent-window.
My first thought was : the SESSION value of the radio-button ---- $_SESSION['my_selection'] --- was not being carried-over into the new (child) window.
But, I used "echo" to verify that this was working properly. The value was indeed being carried-over into the new (child) window.
However, after the child-window closes, and the parent-window is re-directed, I used "echo" again to track any errors........and it showed that : the value of $_SESSION['my_selection'] is always equal to "25" !
In a nutshell : why is the second IF-statement being ignored??
elseif (($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] =
'50')) {
echo '<script type="text/javascript">window.opener.location =
"/PHP/50.php";setTimeout("window.close();", 1000);</script>';
($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] = '25')
^ ^
A single equals sign is an assignment and as the value you are assigning is truthy the if will always evaluate to true. Use == for a comparison.
You are using = instead of == in nearly all statements:
if (($_POST['my_response'] = 'yes')
should be
if (($_POST['my_response'] == 'yes')
This way, you don't check if $_POST['my_response'] is equal to "yes", but if it is possible to assign "yes" to $_POST['my_response']. As a result, all your if statements are true.

Checking for unfilled fields with PHP

I am creating a checkout page that requires the client to fill out his personal information as well as his credit card details (this part using stripe).
I was wondering, what is the best way to check whether the fields are filled up or not? Shall I do it in the processingPayment.php that $_POSTs the fields and processes payment, and in case the fields were not filled, I would redirect back to checkout?
Or is it a better idea to use js to check on the spot before submitting the form?
if in the processing page, I would try something like this:
if (empty($firsName) || empty($lastName) || empty($address) || empty ($city) || empty ($state) || empty($zip))
{
header('Location: checkout.php');
}
But I would need to re-send the values that were entered so the checkout page receives them and the user doesn't have to re-fill every field again...
Something like this?
foreach($_POST as $key=>$val) {
if( empty($val) ) {
echo "$key is empty";
}
}
The best method with PHP is to have an array of possible arguments:
$array = array('firstName', 'lastName');
foreach($array as $val) {
if( empty($_POST[$val]) ) {
echo "$val is empty";
}
}
Otherwise, client side validation works too, but can always be disabled. To be completely safe, use both client and server side.
You can use the session to store the entered data, but you would need to check each value separately:
PHP
<?php
session_start();
foreach ($_POST as $key => $value) {
if (strlen(trim($value)) <= 0) { //You could replace '0'
$_SESSION[$key] = $value;
}
}
?>
FORM
<form>
First name: <input type="text" value="<?php $_SESSION['firstName'] ? $_SESSION['firstName'] : ''; ?>" placeholder="First Name" />
....
</form>
The $_SESSION['firstName'] ? $_SESSION['firstName'] : ''; is the same as
if ($_SESSION['firstName']) return $_SESSION['firstName']
else return '';
it is more readable in the HTML(View) that the full if statement
$var = isset($_POST['field']) ? $_POST['field'] : '';
$var2 = isset($_POST['field2']) ? $_POST['field2'] : '';
// and so on
if( empty($var) || empty($var2) )
{
//it's empty
}

code checks one checkbox or the other, but not both

So basically, I have a function that is ran when a post is created on wordpress. I've modified this function by adding the following code.
$episodeID = $_POST['item_meta'][137];
$episodeVersion = $_POST['item_meta'][357];
if ($episodeVersion == "Subbed") {
$value = array("Subbed");
update_field('field_48', $value, $episodeID);
}
else if ($episodeVersion == "Dubbed") {
$value = array("Dubbed");
update_field('field_48', $value, $episodeID);
}
This code basically says, if the value of a field in that post is "Subbed" then update another checkbox field by checking the "Subbed" checkbox. If it's "Dubbed" then update the checkbox field by selecting the "Dubbed" checkbox.
This works perfectly fine, however there is no time when both of these checkboxes are checked. If I add a post with the Dubbed, it'll check dubbed, then if I add a post with Subbed, it'll uncheck dubbed and check subbed.
So basically, how can I make it so it doesn't actually uncheck whatever has already been checked. So what should I use to check to see if the checkbox is unchecked or checked? Some type of boolean true / false?
Okay, so I was able to manipulate some of the code and get it to work eventually.
All I had to do was check if the Subbed checkbox was already checked when executing the dubbed if statement, and vice versa.
Here is the updated code
$episodeID = $_POST['item_meta'][137];
$episodeVersion = $_POST['item_meta'][357];
if ($episodeVersion == "Subbed" && !(get_field('episode_sdversion') && in_array('Subbed', get_field('episode_sdversion', $episodeID))) ) {
if (get_field('episode_sdversion') && in_array( 'Dubbed', get_field('episode_sdversion'))) {
$value = array("Subbed", "Dubbed");
} else {
$value = array("Subbed");
}
update_field('field_48', $value, $episodeID);
}
if ($episodeVersion == "Dubbed" && !(get_field('episode_sdversion') && in_array('Dubbed', get_field('episode_sdversion', $episodeID))) ) {
if (get_field('episode_sdversion') && in_array( 'Subbed', get_field('episode_sdversion'))) {
$value = array("Subbed", "Dubbed");
} else {
$value = array("Dubbed");
}
update_field('field_48', $value, $episodeID);
}

Php checkbox retrieve data from database

I have:
$array_worker['$worker_id']=$worker_name;
$array_job['$job_id']=$job_name;
I have no problem with dynamic create table with checkbox and store data in database:
The data are stored in table as worker_id,job_id!
Normally, worker may work more than one job, so I create multidimensional array from table in which the stored data!
$array_worded['$worker_id'][]=$job_id;
My question is:
How create dynamic table with checked checkboxes based on array_worked array?
$table='';
foreach($array_worker as $key=>$value){
$table.=''.$value.''; // worker name
$worker_id = // get worker id from $array_worker
foreach($array_job as $key_job=>$val_job)
{
$job_id = // get job id from $array_job
$checked = false;
foreach( $array_worked[$worker_id] as $key_worked => $val_worked )
{
if( $job_id == $val_worked ) // $val_worked contains $job_id
{
$checked = true;
break;
}
}
$table.='<input type="checkbox"' . ( $checked ? ' checked="checked"' : '') . '/>'.$val_job.''; // all jobs from database
}
$table.='';
}
$table.='';
I may make some mistakes in syntax, but code demonstrates basic principle.
It is so simple :
<input type="checkbox" name="formWheelchair"
<?php
$DATABASE-VALUE = $array_worded['$worker_id'][] = $job_id; // OR WHAT EVER
switch ($DATABASE-VALUE) {
case 0:
echo checked />"
break;
........
}
?>

Which checkbox is selected and assigning a value

I am trying to create logic to see what checkbox is selected (of 5 possible checkboxes) and if it is selected assign it a value of 0. if it is not selected I was to assign it a value of 1. The proceeding code snippet highlight this but throws a parse error in my else statement and I cannot fighure out why.
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = 'unchecked';
$chkBox2 = 'unchecked';
$chkBox3 = 'unchecked';
$chkBox4 = 'unchecked';
$chkBox5 = 'unchecked';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
else{
$chkBox1 = '1';
}
}//End of chkBox1Selected logic
You don't understand how checkboxes work. If a checkbox is deselected before posting, it will not be set on post.
Therefore, the only condition that will ever be present in your code is that every value will show as 1, since they cannot be overridden.
Take this snippet and try it out. It dynamically loops for the amount of variables you need and assigns the values based upon the submitted value.
$_POST['chkBox4'] = 'test';
for( $i = 1; $i <= 5; $i++ )
{
$name = 'chkBox' . $i;
$$name = !isset( $_POST[$name] ) ? 0 : $_POST[$name];
}
print $chkBox2 . ' // '. $chkBox4;
http://codepad.org/51RotnCf
Ok I got it to work from a syntax standpoint, however now no matter what is selected it is still assigning a value of 1 to all the checkboxes and not changing the selected checkbox to a value of 0. Here is the new code that is correct from a syntax standpoint but defaults to 1 no matter what:
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = '1';
$chkBox2 = '1';
$chkBox3 = '1';
$chkBox4 = '1';
$chkBox5 = '1';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
}//End of chkBox1Selected logic
if (isset($_POST['chkBox2'])) {
if ($chkBox2 == 'chkBox2Selected') {
$chkBox2 = '0';
}
}//End of chkBox2Selected logic
if (isset($_POST['chkBox3'])) {
if ($chkBox3 == 'chkBox3Selected') {
$chkBox3 = '0';
}
}//End of chkBox3Selected logic
if (isset($_POST['chkBox4'])) {
if ($chkBox4 == 'chkBox4Selected') {
$chkBox4 = '0';
}
}//End of chkBox4Selected logic
if (isset($_POST['chkBox5'])) {
if ($chkBox5 == 'chkBox5Selected') {
$chkBox5 = '0';
}
}//End of chkBox5Selected logic

Categories