I have read several tutorials to try and get my head around this problem. I have my code working fine with the text input box, but I'm trying to pass the radio box to my function as well and use it to get my array value.
I will implement things like form validation and sanitisation later, but now I just want to be able to output the array result within my function, depending on what radio button was selected. This is the code I have tried:
index.php
<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from text input.
$colour = $_POST['colour']; // data from colour radio.
}
?>
...
<form action="/app.php" method="post">
<input type="text" name="name">
<input name="colour" type="radio" value="1">Red
<input name="colour" type="radio" value="2">Blue
<input name="colour" type="radio" value="3">Green
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>">
pngfile.php
<?php
require_once 'functions.php';
$textdata = urldecode($_GET['data']);
$colourdata = urldecode($_GET['colour']);
process($textdata,$colourdata);
exit;
?>
functions.php
<?php
/* Generate Image */
function process($textdata, $colourdata)
{
$colour_array = [
"1" => "#9E2A2B",
"2" => "#3E5C76",
"3" => "#335C67",
];
...
I am stuck with the piece of the code that will take the radio button value (1/2/3) and then look up the equivalent array value and output the colour, i.e: if radio button with value 1 is selected, then we output 1#9E2A2B.
<form action="/app.php" method="post">
form method POST not GET
$_GET['colour'] edit to $_POST['colour']
in function
function process($textdata, $colourdata)
{
$colour_array = [
"1" => "#9E2A2B",
"2" => "#3E5C76",
"3" => "#335C67",
];
$color = isset($colour_array[$colourdata]) ? $colour_array[$colourdata] : false;
...
Related
im writing a code in php that need to take a data from html form.
i have few radio bottom and few checkbox bottom.
should i have for every bottom/label do varieble in php?
for example:this is from html
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" name="cats">חתולים<br/>
<input type="checkbox" name="dogs">כלבים<br/>
<input type="checkbox" name="hamsters">אוגרים<br/>
<input type="checkbox" name="goldfish">דגי זהב<br/>
<input type="checkbox" name="human">בני אדם
</td>
</tr>
for php:
if (isset($_POST["name"]))
{
$userName = $_POST["name"];
$userYearOfBirth = $_POST["yearOfBirth"];
$soulmate = $_POST["radio"];
}
It would be better to group the checkbox choices so you can access them as an array on the server in PHP. Additionally, move the name of the choice into the value of the checkbox. The new "name" will be whatever you want to call the checkbox group. I am using Animals for this example:
<form name="your-form-name" action="your-form-action-url" method="post">
<table>
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" value="cats" name="animals[]">חתולים<br/>
<input type="checkbox" value="dogs" name="animals[]">כלבים<br/>
<input type="checkbox" value="hamsters" name="animals[]">אוגרים<br/>
<input type="checkbox" value="goldfish" name="animals[]">דגי זהב<br/>
<input type="checkbox" value="human" name="animals[]">בני אדם
</td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
On the server-side if users select more than one animal, all choices will be available in an array like this:
Array
(
[0] => cats
[1] => dogs
[2] => hamsters
[3] => goldfish
[4] => human
)
If they just select one, it'll still be an array:
Array
(
[0] => cats
)
Either way getting the results as an array lets you do something similar with the results whether they chose one or many choices from the list.
You can loop through all the choices and do whatever you need to with the data:
if (isset($_POST['animals'])) {
$animals = $_POST['animals'];
foreach ($animals as $key => $value) {
// do something with each $value .. maybe add to a database? echo back to user?
}
}
You actually don't need any new variables. You can use $_POST array as the variables.
Example (form side):
<form method="post">
<input type="text" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
echo $_POST['test']; // This will echo the input that named "test".
?>
The example above is valid for every method and input types.
In your case, your checkboxes will output "true" or "false" (Unless you define a value for the checkbox. If you define a value to it, it will output the defined value if the checkbox is checked.).
Example (form side):
<form method="post">
<input type="checkbox" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
if ($_POST['test'] === true)
echo "Yay! The checkbox was checked!";
else
echo "Oops! The checkbox wasn't checked!";
?>
Sorry for what is probably quite an easy question, but I'm trying to pick up some info from my php form:
This is my current code which works for the post name, but what if I want to also grab the colours boxes that were selected too?
main.php
<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from the form input.
}
$colour_array = [
"red" => "#9E2A2B",
"blue" => "#3E5C76",
"green" => "#335C67",
];
?>
...
<form action="/" method="post">
<input type="text" name="name" placeholder="Acme Corp"/>
<input name="colour" type="checkbox" value="red">Red<br>
<input name="colour" type="checkbox" value="blue">Blue<br>
<input name="colour" type="checkbox" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>"
alt="png php file">
I guess I confused because currently it is calling this:
pngfile.php
<?php
require_once 'functions.php'; // Requires and includes do not need brackets.
$inputData = urldecode($_GET['data']);
process($inputData);
exit;
?>
Which calls functions.php
<?php
function process($inputdata)
{
...
The issue is I want to be able to separate out the values from the form, so I get both the input box and the colour selection in separate variables.
EDIT: What I have tried:
main.php
$data = $_POST['name'] && $_GET['colour']
functions.php
process($inputdata, $colours)
But I'm not really sure where to go from there.
In HTML, change name="colour" to name="colour[]"
To access the value of colour in php do something like below
<?php
if(!empty($_POST['colour'])) {
foreach($_POST['colour'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
}
}
?>
I am trying to save some values into db, on first page i am running some matches and on the the 2nd page i need to save values. on first page only click button is shown to user, when he clicks , the values are stored.
code
<form action="ms_insert.php" method="post">
<input type="submit" value="Claim your daily bonus" name="test">
</form>
How can i submit all the values that are outside the form and send them to the ms_insert.php and process the values.
What i need to achieve it like this.
some values shall be matched , on successful match it will save the enteries into the db.
Here is the exact code that i am using now :
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo "wrong";
}
?>
<form action="" method="post">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="claim">
</form>
I want this php code to excute when user click the submit button.
There are two ways that I can think of doing this:
Simply set the post variable to another value as described here:
$_POST['text'] = 'another value';
This will override the previous value corresponding to text key of the array. The $_POST is super global associative array and you can change the values like a normal php array.
Second would be to use _SESSION tags as described in this post:
In the first.php:
$_SESSION['favcolor'] = 'green';
In ms_insert.php:
echo $_SESSION['favcolor']; // green
P.S. You can also use cookies
Additional sources:
http://www.felixgers.de/teaching/php/hidden1.html
You can use Javascript with a XHR object for example or try to insert your values to store in hidden inputs.
Solution 1 : AJAX, for example :
Your JS (Here with Jquery):
function saveInDb(){
/* Retrieve your values in your page : */
var myValue1 = $('#value1Id').val();
var myValue2 = $('#value2Id').val();
/*Create a Jquery ajax object : */
$.ajax({
type: "POST",
url: "ms_insert.php",
data: { "value1": myValue1, "value2": myValue2 }
}).done(function( msg ) {
alert( "Data Saved");
});
}
Your HTML :
<span id="value1Id">My value 1</span>
<span id="value2Id">My value 2</span>
<button onclick=saveInDb()></button>
Solution 2 : the HTML with hidden inputs :
<form action="ms_insert.php" method="post">
<input type="hidden" value="My value 1" name="value1">
<input type="hidden" value="My value 2" name="value2">
<input type="submit" value="Claim your daily bonus" name="test">
</form>
<form action="" method="post">
<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />
<input type="submit" name="foo" value="C" />
<input type="submit" name="foo" value="D" />
</form>
<?php
$letters = $_POST['foo'];
?>
each time form submit $letters will be filled with respective values. so $letters can be "A" or "B" or "C" etc.
is it possible store all submitted values at a time? say when I echo $letters it should give "ABCD" or "BCDBA" or whatever order form is submitted.
I think this can be done through $_SESSION but no Idea how...any ideas?
Hy
Try make the attribute name in each submit button: name="foo[]"
Then, in php, $_POST['foo'] contains an array with the value of each "foo[]"
echo implode('', $_POST['foo']);
You could use the session, so first: $_SESSION['letters']=array(); and then each post you can do $_SESSION['letters'][] = $_POST['foo']; and then you will have an ordered array.
This is how the top of your page will look:
session_start(); //important that this is first thing in the document
if ( !$_SESSION['letters'] ) {
$_SESSION['letters'] = array(); //create the session variable if it doesn't exist
}
if ( $_POST['foo'] ) { //if foo has been posted back
$_SESSION['letters'][] = $_POST['foo']; // the [] after the session variable means add to the array
}
You can use print_r $_SESSION['letters']; to output the array as a string, or you can use any of the many php array functions to manipulate the data.
Try this
$email_to = "";
$get= mysql_query("SELECT * FROM `newsletter`");
while ($row = mysql_fetch_array($get)) {
$email_to = $email_to.",".$row['mail'];
}
echo $email_to;
I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.