Radio button how to? - php

what i want to do is that when you vote Y or N (two different radio buttons) and then it inserts into the "vote" column(in database) = Y or N(what you pickd), if nothing then echo error.
I know how to do this like halfway, i never worked with radiobuttons before so i need you guys.
Here's a two radio button right:
Yes: <input type="radio" value="Y" id="voteYes" name="vote"></input> <br>
No: <input type="radio" value="N" id="voteNo" name="vote"> </input>
I gave the value N and Y, not the same ID, but the same name. I think its right, but how should i do with the PHP part of what i want to do? I mean shall i call for "vote"? ($_GET["vote"]) i dont think so.. here's where im stuck

You're almost there. Depending on whether or not your form uses the GET or POST method, you'll have to change the variable name appropriately.
if(isset($_GET["vote"])) //checks to see if the user inputed something
{
$value = $_GET["vote"]; //remember, this value is not guaranteed to be either Y or N
}
else
{
//display your error
}

Why not? Just make sure you validate your data... make sure $_GET['vote'] must be an element of array('Y', 'N'), if true you insert it, else echo error and you're done.

POST variables are found in $_POST.
echo $_POST['vote'];

It depends on the method used. If you POST the form, then the variable will be $_POST['vote'], if you GET the form (default) then it will be $_GET['vote'].
Specify the method used in the form tag:
<form action="foo.php" method="POST">
or...
<form action="foo.php" method="GET">
Check for the existance of the variable either with isset() or array_key_exists().

Related

Trying to get value of checkbox from form to controller

I'm trying to do something that allows me to upload photos when I check a checkbox control. I got the client side working correctly such that when the checkbox is checked the upload controls are displayed and the form validates correctly.
However, in my controller I need to take some action if my checkbox was checked (true) calling a certain method. If it isn't checked (false) I perform some other action.
In my html page I have the following:
<form action="/supplier/submit/plan" method="post" role="form" id="plan-form">
...
<input name="checkingPhotos" type="checkbox" id="chkPhotos" />
<label for="chkPhotos">I want to include photos in this plan.</label>
...
</form>
However, in my controller I just want to for now see if I get the correct value in my checkbox. For this I did something simple as:
public function submitPlan(Request $request)
{
$checkboxValue = $request->input('checkingPhotos');
dd($checkboxValue);
}
The result is null is printed whether I check the checkbox or not. My route also looks like this:
Route::post('/submit/plan', 'SupplierController#submitPlan');
Can someone please tell me what I am doing wrong here? I just want to see the value 1 / True or 0 / False in my controller method.
Value
The real issue is that you don't have a value for your check box. Add a value, and your problem is solved. It should be:
<input name="checkingPhotos" type="checkbox" id="chkPhotos" value="1" />
[] creates an array
The answer Dylan Kas submitted about changeing the name to add [] works, but not for the reasons you think. Lets take a look:
<input name="checkingPhotos[]" type="checkbox" id="chkPhotos" />
Will pass in the post string:
checkingPhotos[]=On
Which, in PHP will automatically be turned into an array.
Refernce Frame Challenege
Why do you have a checkbox in the first place? Is the checkbox needed? Why not just check for the existence of the file.
$validated = $request->validate([
//... other fields here.
'image' => 'mime:png,gif,jpeg|max:10000' //set max to file size limit you want
]);
$plan = new SupplierPlan($validated);
if($request->has('image')){
$plan->image = $request->image->store();
}
$plan->save();
// ... flash message, return view or redirect
If it's a checkbox you should modify the name of your input to
<input name="checkingPhotos[]" type="checkbox" id="chkPhotos" />
Then you should be able to get the value as you want it with
$request->input('checkingPhotos');
It seems your problem is in your route, change it to
Route::post('/supplier/submit/plan', 'SupplierController#submitPlan');

PHP: Submitting form data via $_POST works for all fields except radio buttons

I am new to PHP and hope someone can help me with this.
I have an HTML form with a number of inputs and textareas. On Submit I pass the form to another PHP page that generates an email with its values.
For text inputs and textareas everything works as intended but for the radio buttons I can't get it to show me the value on the targetted page.
The radio buttons look as follows and the classes used there are only to apply some CSS.
There is only one form on the submitting page, all radios have the same name ("requestType") and there are no other elements using this name.
Also, I added a quick JavaScript snippet for testing to alert their value on change and this worked as well, so the issue seems to be only with the $_POST.
Can someone tell me what I am doing wrong here or what alternatives I could try here ?
My HTML (on the submitting page):
<input type="radio" class="customRadio radioDefault" id="requestType1" name="requestType" value="Value1" />
<label for="requestType1">Value1</label>
<input type="radio" class="customRadio triggerDiv" id="requestType2" name="requestType" value="Value2" />
<label for="requestType2">Value2</label>
My PHP (on the targetted page):
$_POST["requestType"]
Update:
As per RiggsFolly I tried to check whether it recognises that a radio button is checked which it seems it does, it just doesn't return anything as the following just returns "xx":
if(isset($_POST['requestType'])){
$theSelectedOne = $_POST['requestType'];
echo "radio value: x" . $theSelectedOne . "x";
}else{
echo "boohoo";
}
Radio buttons (and Checkboxes) are only passed back to the form in either the $_POST or $_GET arrays if they are actually checked. I notice you do not auto check one of them as you create the HTML so nothing is likely to be returned if the user makes no selection.
So the best way to test if they were checked or not is to test for the existance of their name in the $_POST array
if ( isset( $_POST['requestType'] ) ) {
// a selection was made
// so now test the value to see which one was checked
$theSelectedOne = $_POST['requestType'];
}

Passing checkbox state to PHP

<input type="hidden" name="check_box_1" value="0" />
<input type="checkbox" name="check_box_1" value="1" />
This works fine, however when you click on submit, and the checkbox is ticked, it passes BOTH the hidden value and the original checkbox value to the $_POST variable in php, can this be avoided?
I have the hidden value there, so that unticked checkboxes are passed to the $_POST variable as well as the ticked ones.
The better approach is to remove the hidden field, and simply have a check in PHP:
if ($_POST['check_box_1']=='1') { /*Do something for ticked*/ }
else { /*Do something for unticked*/ }
You shouldn't need the hidden field. You should in fact not trust any of the form fields sent in the first place. What this means is that you cannot make code which takes the sent fields and trust them to send the correct data (which I assume you do now).
What you should do is to handle all fields you expect to get. That way if you don't get the checkbox value you can still handle that as if it was unticked. Then you also get the added inherent feature of throwing away form data you don't expect in the first place.
No, it will pass all the form data, whatever it is. The right way to do this is not to set the checkbox via a hidden field but to set the checkbox with whatever its state actually is!
I mean... why are you adding the hidden field to begin with?
Your PHP is receiving two fields named check_box_1, and last time I checked there was no way to guarantee that the params would get read into the REQUEST hash in the exact same order as you sent them, so, there's no way to tell which one will arrive last (that's the one whose value will get set). So... this is not the right approach to whatever problem you're trying to solve here.
Welcome to Stack, btw! If you find answers useful or helpful, make sure to mark them as correct and vote them up.
That's normal.
They must be both type="checkbox" to pass only 1 value.
If you want to get only 1 in any cases you can do:
<input type="checkbox" style="display:none;" name="check_box_1" value="0">
Make sure the first input field is of type Checkbox, or else it won't behave like one.
<input type="checkbox" name="check_box_0" value="0" />
<input type="checkbox" name="check_box_1" value="1" />
Everything is working normal with your code so far.
I'm assuming you are creating the hidden field so that 0 is passed to the server when the checkbox is not checked. The problem is that they both get passed when the check box is checked.
As Death said, the way you should be doing it is with a single checkbox and then checking if the value has been sent to the server or not. That's just how checkboxes work.
If you want to have a default set then you will have to handle all that on the server side based on weather the checkbox has a value.
For example:
$myValue = "";
if(isset($_POST['check_box_1']))
{
$myValue=$_POST['check_box_1'];
}
else
{
$myValue="0";
}

Update MySQL DB with PHP from Checkbox

I am pulling data down from a MySQL table and loading it into a form for editing(updating) a record. Everything is working great until I come the the check boxes. The checkboxes in the form accurately reflect the values in the appropriate columns in the db. But when the person editing changes the checkbox in the edit form it does not pass the data to the database. I have read a ton of checkbox Q&A on stack overflow but don't seem to find what I am looking for. Sorry if this is a redundant Question. Here is the code.
<label for="amenities-beach">
<input class="choose" name="amenitiesB" id="amenities-beach" type="checkbox"
value="<?php echo $row1["amenitiesB"]; ?>"
<?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
Close to Beach</label>
Where amenitiesB in:
value="<?php echo $row1["amenitiesB"]; ?>
is what has been returned from the DB with a SELECT statement with:
$row1 = mysql_fetch_array($result);
But when I change the value in the form and submit it nothing is passed to the variable in the UPDATE statement. Any idea what I am missing? I have 6 of these checkboxes,amenitiesB, amenitiesK, amenitiesS, amenitiesP, amenitiesF, and preferred all with the same code. Any help would be appreciated.
Thank You,
Dave
Ok here is the code: Everything else in the form updates fine. I attempt to pass it to:
$amenitiesB = $_POST['amenitiesB'];
then I put it into the update statement
Hotels.amenitiesB='".$amenitiesB."',
My UPDATE statement is,
$query="UPDATE Hotels
JOIN surfcup_Rates ON Hotels.id = surfcup_Rates.hotelid
SET Hotels.hotel='".$hotel."',
More columns, then
Hotels.amenitiesB='".$amenitiesB."',
Hotels.amenitiesB='".$amenitiesK."',
Hotels.amenitiesB='".$amenitiesS."',
Hotels.amenitiesB='".$amenitiesP."',
Hotels.amenitiesB='".$amenitiesF."',
Hotels.amenitiesB='".$preferred."',
More columns then:
WHERE Hotels.id='".$id."'";
The problem you have comes because when a checkbox is unchecked, by default its data is not transmitted to your PHP, and that's why you have problems by having the UPDATE query parameter empty.
So before your update statement you should have:
$fieldenabled=(bool)(isset($_POST['CHECKBOXNAME']) ? TRUE : FALSE;
And call your UPDATE query with that.
EDIT: Of course you can change $_POST with $_GET depending on the sending method of the <form>
Edit: I think I get the problem. When the box is initially unchecked, the input has an empty value, then when you check it, it passes an empty value in... it will never fill with what you intend the checked value to be. So, instead you need something like this:
<input class="choose" name="amenitiesB" id="amenities-beach" type="checkbox" value="amenity B Selected" <?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
... don't make the "value" attribute dynamic, or else once it becomes empty it will always be empty.
Original Answer:
I assume when you say "change the value in the form" you mean that you uncheck the checkbox... unchecked checkboxes never send any data when you submit the form. You check for "unchecked" status by checking to see if the form variable has been passed at all.
For example:
if (isset($_GET['amenitiesB'])) {
// process with the knowledge that "amenitiesB" was checked
}
else {
// process with the knowledge that "amenitiesB" was unchecked
}
If you mean that you somehow dynamically change the "value" of the checkbox to something else, then I'll need to see the code that accomplishes that.
The main purpose of the "value" attribute in a checkbox input is when you're passing the variable as an array:
<label for="amenities-beach">
<input class="choose" name="amenities[]" id="amenities-beach" type="checkbox" value="<?php echo $row1["amenitiesB"]; ?>" <?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
Close to Beach
</label>
... note specifically that I've changed the "name" attribute from "amenitiesB" to "amenities[]", which, if carried through all of your amenities checkboxes, will give you access to them all in your processing script through the $_GET['amenities'] array (or $_POST, if applicable). Otherwise, there's not much reason to use the "value" attribute of the checkbox input, because you can get all you need just by knowing $_GET['amenitiesB'] is checked (and thus sent with the form) or unchecked (and not sent with the form).

$_POST not finding a "name" value

I am trying to submit a form, it SHOULD send forth a name, but I know I'm messing something silly up and I just can't see it (3 hours of sleep last night + new coding project at work != a smart idea)
Here's my form on one page:
<form action="add.php" method="POST">
<button type="submit" name="exportcult">Export All</button>
</form>
And here's the code on the other page, meant to process the POST:
if (!isset($_POST["name"]) || $_POST["name"] == '') {
header('Location: '.$criteria."?error=data");
die();
}
I am getting the error message this sends back, so I know it isn't registering a name - why could that be?
I think you're confused how the form data actually gets submitted. "name" is the attribute, not the key value that is found in the POST data. You need to specify the name for that element, which will be the key value present in the POST data. You have specified name="exportcult" so in the POST data, the variable will be at $_POST['exportcult']. However, this value will always be an empty string since you have not indicated a value attribute for your button.
Keep in mind that when dealing with submit buttons, only the value of the button which was used to submit the form will be included along with the rest of the form data. Try using this:
<button type="submit" name="exportcult" value="export">Export All</button>
If that specific button was used to submit the form, then $_POST['exportcult'] should be equal to 'export'.
For those of you who are unsure: buttons do get submitted with the form, but they still have to have a value attribute.
Your form doesn't contain any field except the button, so $_POST will only contain a field exportcult.
Edit: Since you use <button> instead of <input> it might not go into the POSTed data.
Do:
if (!isset($_POST["exportcult"]) || $_POST["exportcult"] == '') {
header('Location: '.$criteria."?error=data");
die();
}
You're currently checking for a field named "name", when the field is named "exportcult". Additionally, it should be <input, not <button.
you should add
<input type="button" name="exportcult" value="Whatever you want" />
and check for exportcult on the isset() instead of name
use exactly this:
<form action="add.php" method="POST">
<input type="submit" name="name" value="Export All"></form>
if (!$_POST["name"])) {
header('Location: '.$criteria."?error=data");
exit();
}

Categories