I would like to store an user input from a textbox into an external php array by clicking a button. Also, there is a dependency from two radio buttons.
This is my current attempt:
At first, I include the external php array:
<?php
include ('../array.php');
?>
The input form:
<form action="" method="post">
<input type="text" name="textfield" id="txt1" value="">
<input type="radio" name="name" id="id" value="Type1">Type1<br>
<input type="radio" name="name" id="id" value="Type2">Type2<br>
<button id="submit" name="send" type="submit">Save</button>
</from>
Insert the value into the array:
<?php
if (isset($_POST['send'])){
if (isset ($_POST['name'])){
if ($_POST['name']=='Type1'){
$newword = $_POST['textfield'];
$array[] = $newword;
}
}
}
?>
But the values don't "stack", meaning that the array isn't growing with each button click.
Can anyone help please? :D
Thanks in advance!
If you want to stack values, you need to store them somewhere to keep values between each requests to server.
Values can be stored in session (for current user only) or in any database supported by PHP.
Here an example with session :
index.php :
<?php
include ('./array.php');
?>
<form action="" method="post">
<input type="text" name="textfield" value="">
<input type="radio" name="name" value="Type1">Type1<br>
<input type="radio" name="name" value="Type2">Type2<br>
<button id="submit" name="send" type="submit">Save</button>
</from>
array.php :
<?php
session_start();
if (!is_array($_SESSION['persistentValues'])) {
$_SESSION['persistentValues'] = array();
}
if (isset($_POST['send']) && isset($_POST['name']) && $_POST['name']=='Type1') {
$_SESSION['persistentValues'][] = $_POST['textfield'];
}
print_r($_SESSION['persistentValues']);
?>
<form action="" method="post">
<input type="text" name="textfield" id="txt1" value="">
<input type="radio" name="name" id="id" value="Type1">Type1<br>
<input type="radio" name="name" id="id" value="Type2">Type2<br>
<button id="submit" name="send" type="submit">Save</button>
</from>
in the file php put this
<?php
if (isset($_POST['send']) && $_POST['textfield'] && $_POST['name']){
if ($_POST['name']=='Type1'){
array = require('./array.php');
$newword = $_POST['textfield'];
$array[] = $newword;
}
}
?>
Related
How can I send a radio or checkbox value to the $_POST array even when the field is empty?
<?php
if(isset($_POST)) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
?>
<form action="test.php" method="POST">
<input type="text" name="name">
<input type="text" name="email">
<input type="radio" name="gender">
<input type="submit">
</form>
Here is what I get from the page if I hit submit without even filling out data.
Array
(
[name] =>
[email] =>
)
As you see, without touching the input type text, their value was pushed to the $_POST array. How can I do this with the radio box? I essentially want to "set" it, although it is blank just like the text inputs.
I know I could always call
<?php
if(isset($_POST['gender'])) {
//Code
}
?>
But that's not necessarily what I'm looking for. I need it to set automatically. Thanks in advance!
Try this it will work :
Unchecked radio 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.
<?php
if(isset($_POST)) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
?>
<form action="test.php" method="POST">
<input type="text" name="name">
<input type="text" name="email">
<input type="radio" name="Gender" value="1"/>Male
<input type="submit" name="submit" value="submit"/>
</form>
Should be :
HTML :
<form action="test.php" method="POST">
<input type="text" name="name">
<input type="text" name="email">
<input type="radio" name="gender" value="male"/>Test
<input type="submit" name="submit" value="submit"/>
</form>
PHP Code :
if(isset($_POST['submit']))
{
echo $radio_value = $_POST["radio"];
}
Consider this example:
// Set a default value as male
<input type="radio" name="gender" checked value="male"> Male
<input type="radio" name="gender" value="femail"> Female
and you will get the value
Array
(
[name] =>
[email] =>
[gender]=>male
)
You only get the checked radio in the $_POST array
If you want to send blank value automatically then
By default checked that radio button and set blank value:
<form action="test.php" method="POST">
<input type="text" name="name">
<input type="text" name="email">
<input type="radio" name="gender" value='' checked>
<input type="submit">
</form>
HTML :
<form action="test.php" method="POST">
<input type="text" name="name">
<input type="text" name="email">
<input type="radio" name="gender" checked value="male"/>Male
<input type="radio" name="gender" value="female"/>Female
<input type="submit" name="submit" value="submit"/>
</form>
PHP :
if(isset($_POST)) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
<form action="" method="POST">
<input type="text" name="name">
<input type="text" name="email">
<input type="radio" name="gender" checked value="male"> Male
<input type="radio" name="gender" value="femail"> Female
<input type="submit" value="submit">
</form>
<?php
if(isset($_POST)) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
?>
Now i have 4 buttons on my page. They define different parameters. What i want to do, is use php switch case, and after pressing for example button1 i want the datetimepicker, and a chart appear as well. I read that i can manage with that problem using two html forms in one php file adding form id, but im only getting the first form to work properly while the second one seems to fail with sending the data using POST method. Below how i try to do this:
<form id="switch" action="data-from-database.php" method="post">
<h2 align="center">Wybierz interesujący Cię przedział
czasowy</h2></br>
<div id="pudlo">
<input type="submit" name="przycisk"
class="input_wykresy" value="temperatura" form="switch">
<input type="submit" name="przycisk"
class="input_wykresy" value="wilgotność" form="switch">
<input type="submit" name="przycisk"
class="input_wykresy" value="ciśnienie" form="switch">
<input type="submit" name="przycisk"
class="input_wykresy" value="irradiancja" form="switch">
</div>
</form>
<?php
//PHP part here is what i want to appear on the page after using switch
switch ($_REQUEST['przycisk'])
{
case "temperatura":
//Once again HTML part
?>
<form id="picker" action="data-from-database.php" method="post">
<input type="text" name="from_date"
id="from_date" class="input_wykresy1" placeholder="Od" autocomplete="off">
<input type="text" name="to_date" id="to_date"
class="input_wykresy1" placeholder="Do" autocomplete="off">
<input type="submit" name="filter" id="filter" value="Wyszukaj"
form="picker" class="input_wykresy"/>
</form>
<?php
if (isset($_POST["from_date"], $_POST["to_date"])) // php code which i want to work in case
{
$handle = $link->prepare("SELECT temperatura, czaspomiaru FROM Pomiary
WHERE czaspomiaru BETWEEN'" . $_POST["from_date"] . "' AND
'" . $_POST["to_date"] . "'");
}
$dataPoints = [];
//Best practice is to create a separate file for handling connection to database
try
{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
if ($result)
{
foreach ($result as $row)
{
array_push($dataPoints, ["label" => $row->czaspomiaru, "y" =>
$row->temperatura]);
}
}
else
{
?>
<div>
<h2>
<center>Nie znaleziono pasujących rezultatów</center>
<h2>
</div>
<?php
}
$link = null;
}
catch (\PDOException $ex)
{
print($ex->getMessage());
}
}
First form working properly, which i tested on buttons. Second one doesnt work, because when i press the submit button refering to datetimepickers, nothing shows on chart i assume no data been sent. I wonder how can i get the second form working?
You might want a hidden field holding the name/value pair of the button taking you to the subform since the button is not part of that form.
<form id="picker" action="data-from-database.php" method="post">
<input type="hidden" name="przycisk" value="temperatura">
<input type="text" name="from_date"
id="from_date" class="input_wykresy1" placeholder="Od" autocomplete="off">
<input type="text" name="to_date" id="to_date"
class="input_wykresy1" placeholder="Do" autocomplete="off">
<input type="submit" name="filter" id="filter" value="Wyszukaj"
form="picker" class="input_wykresy"/>
</form>
Or, since you do not use the submit button name="filter" in your PHP code, you could just alter that button.
<form id="picker" action="data-from-database.php" method="post">
<input type="text" name="from_date"
id="from_date" class="input_wykresy1" placeholder="Od" autocomplete="off">
<input type="text" name="to_date" id="to_date"
class="input_wykresy1" placeholder="Do" autocomplete="off">
<input type="submit" id="filter" name="przycisk" value="temperatura"
form="picker" class="input_wykresy"/>
</form>
Consider using four radio buttons (instead of four submit buttons). Your site visitor(s) can select which radio button and submit. The code could easily be handled with if, elseif, else conditions, and the output could appear in one designated area, regardless of which radio button was selected.
<form id="switch" action="data-from-database.php" method="post">
<h2 align="center">Wybierz interesujacy Cie przedzial
czasowy</h2></br>
<div id="pudlo">
<input type="radio" name="przycisk" class="input_wykresy" value="temperatura">
<input type="radio" name="przycisk" class="input_wykresy" value="wilgotnosc" >
<input type="radio" name="przycisk" class="input_wykresy" value="cisnienie" >
<input type="radio" name="przycisk" class="input_wykresy" value="irradiancja" >
<input type="submit" value="submit">
</div>
</form>
<?php
if (przycisk === "temperatura") {
echo "yada";
} elseif (przycisk === "wilgotnosc") {
echo "yada";
} elseif (przycisk === "cisnienie") {
echo "yada";
} else {
echo "yada";
}
?>
So I have a form which is build up like:
<input name="website['menu']['id']" type="number" value="1">
<input type="text" value="#000000" name="website['color']['primary']['hex']">
Now i want to read out those values in php after they are submit.
I tried the following code, but when I var_dump it it gives me null.
if (isset($_POST['website'])) {
$result = $_POST['website'];
var_dump($result['menu']['id']);exit;
}
Remove the quote from field name
<input name="website[menu][id]" type="number" value="1">
<input type="text" value="#000000" name="website[color][primary][hex]">
And access the variable in php like:
echo $_POST['website']['menu']['id'];
Try this,
<?php
print_r($_POST['website']);
print_r($_POST['website']['menu']['id']);
?>
<form action="" method="POST"/>
<input name="website[menu][id]" type="number" value="1">
<input type="text" value="#000000" name="website['color']['primary']['hex']">
<input type="submit" value="submit"/>
</form>
I have this form:
<form action="" method="post">
<label for="color">Color:</label>
<input type="text" style="width: 195px;" name="color" id="color" value="<?php echo $item; ?>">
<input value="Save" type="submit" />
</form>
And the following PHP to capture contents:
if (!empty($_POST['color']) && preg_match('/^#[a-fA-f0-9]{6}/', $_POST['color']) != 0 ) {
$thisarray[] = $_POST['color'];
SetProfileField('usercss', $USER->id, implode(',',$thisarray));
}
How can I add a new field to the Form and then add that to the array to be saved?
You can add new fields to the form if you alter the HTML code. There are many different form elements, see if there is something you need here: http://www.w3schools.com/html/html_forms.asp
You can access the value of each element with $_POST['key'], so to add it to the array you would have to write $thisarray[] = $_POST['key']. Note: Replace key with the actual name of the form element.
Whole Example:
HTML:
<form action="" method="post">
<label for="color">Color:</label>
<input type="text" style="width: 195px;" name="color" id="color" value="<?php echo $item; ?>">
<input name="the_new_element" />
<input value="Save" type="submit" />
</form>
PHP:
if (!empty($_POST['color']) && preg_match('/^#[a-fA-f0-9]{6}/', $_POST['color']) != 0) {
$thisarray[] = $_POST['color'];
$thisarray[] = $_POST['the_new_element'];
SetProfileField('usercss', $USER->id, implode(',',$thisarray));
}
I named the field the_new_element, change this to whatever you want. Of course you should also sanitzie the contents.
I'm trying to create a BMI calculator. This should allow people to use either metric or imperial measurements.
I realise that I could use hidden tags to solve my problem, but this has bugged me before so I thought I'd ask: I can use $_POST['variableName'] to find the submitted variableName field-value; but...I don't know, or see, how to verify which form was used to submit the variables.
My code's below (though I'm not sure it's strictly relevant to the question):
<?php
$bmiSubmitted = $_POST['bmiSubmitted'];
if (isset($bmiSubmitted)) {
$height = $_POST['height'];
$weight = $_POST['weight'];
$bmi = floor($weight/($height*$height));
?>
<ul id="bmi">
<li>Weight (in kilograms) is: <span><?php echo "$weight"; ?></span></li>
<li>Height (in metres) is: <span><?php echo "$height"; ?></span></li>
<li>Body mass index (BMI) is: <span><?php echo "$bmi"; ?></span></li>
</ul>
<?php
}
else {
?>
<div id="formSelector">
<ul>
<li>Metric</li>
<li>Imperial</li>
</ul>
<form name="met" id="metric" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">
<fieldset>
<label for="weight">Weight (<abbr title="Kilograms">kg</abbr>):</label>
<input type="text" name="weight" id="weight" />
<label for="height">Height (<abbr title="metres">m</abbr>):</label>
<input type="text" name="height" id="height" />
<input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
</fieldset>
<fieldset>
<input type="reset" id="reset" value="Clear" />
<input type="submit" id="submit" value="Submit" />
</fieldset>
</form>
<form name="imp" id="imperial" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">
<fieldset>
<label for="weight">Weight (<abbr title="Pounds">lbs</abbr>):</label>
<input type="text" name="weight" id="weight" />
<label for="height">Height (Inches):</label>
<input type="text" name="height" id="height" /
<input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
</fieldset>
<fieldset>
<input type="reset" id="reset" value="Clear" />
<input type="submit" id="submit" value="Submit" />
</fieldset>
</form>
<?php
}
?>
I verified that it worked (though without validation at the moment -I didn't want to crowd my question too much) with metric; I've added the form but not the processing for the imperial yet.
To identify the submitted form, you can use:
A hidden input field.
The name or value of the submit button.
The name of the form is not sent to the server as part of the POST data.
You can use code as follows:
<form name="myform" method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="frmname" value=""/>
</form>
You can do it like this:
<input type="text" name="myform[login]">
<input type="password" name="myform[password]">
Check the posted values
if (isset($_POST['myform'])) {
$values = $_POST['myform'];
// $login = $values['login'];
// ...
}
The form name is not submitted. You should just add a hidden field to each form and call it a day.
In the form submitting button (id method of form is post):
<input type="submit" value="save" name="commentData">
In the PHP file:
if (isset($_POST['commentData'])){
// Code
}
For some reason, the name of the submit button is not passed to the superglobal $_POST when submitted with Ajax/jQuery.
Use a unique value on the submit button for each form like so
File index.html
<form method="post" action="bat/email.php">
<input type="text" name="firstName" placeholder="First name" required>
<input type="text" name="lastName" placeholder="Last name" required>
<button name="submit" type="submit" value="contact">Send Message</button>
</form>
<form method="post" action="bat/email.php">
<input type="text" name="firstName" placeholder="First name" required>
<input type="text" name="lastName" placeholder="Last name" required>
<button name="submit" type="submit" value="support">Send Message</button>
</form>
File email.php
<?php
if (isset($_POST["submit"])) {
switch ($_POST["submit"]) {
case "contact":
break;
case "support":
break;
default:
break;
}
}
?>
As petervandijck.com pointed out, this code may be susceptible to XSS attacks if you have it behind some kind of log-in system or have it embedded in other code.
To prevent an XSS attack, where you have written:
<?php echo "$weight"; ?>
You should write instead:
<?php echo htmlentities($weight); ?>
Which could even be better written as:
<?=htmlentities($weight); ?>
You can use GET in the form's action parameter, which I use whenever I make a login/register combined page.
For example: action="loginregister.php?whichform=loginform"
I had a similar problem which brought me to this question. I reviewed all the preceding answers, but ultimately I ending up figuring out my own solution:
<form name="ctc_form" id="ctc_form" action='' method='get'>
<input type="hidden" name="form_nm" id="form_nm">
<button type="submit" name="submit" id="submit" onclick="document.getElementById('form_nm').value=this.closest('form').name;">Submit</button>
</form>
It seamlessly and efficiently accomplishes the following:
Passes the form name attribute via a hidden input field, without using the fallible value attribute of the submit button.
Works with both GET and POST methods.
Requires no additional, independent JavaScript.
You could just give a name to the submit button and do what needs to be done based on that. I have several forms on a page and do just that. Pass the button name and then if button name = button name do something.
Only the names of the form fields are submitted, but the name of the form itself is not. But you can set a hidden field with the name in it.