This title might not describe my question too well but I was unsure how to name this post... Anyways, I have a form that has dynamically generated input boxes that pulls the last 4 years with the following:
<?php
$current_date = new DateTime();
for ($i = 1; $i <= 4; $i++) {
$current_date->modify('-1 year');
$date_string = $current_date->format('Y')
?>
<fieldset name="gross_sales">
<input type="number" name="year_brand_gross[<?php echo $date_string; ?>]" placeholder="Gross Sales for <?php echo $date_string; ?>">
</fieldset>
<?php
} // end while
?>
And once the user clicks submit the form data is processed via my process.php file that contains the following:
$year_brand_gross[1] = $_POST['year_brand_gross'][1];
$year_brand_gross[2] = $_POST['year_brand_gross'][2];
$year_brand_gross[3] = $_POST['year_brand_gross'][3];
$year_brand_gross[4] = $_POST['year_brand_gross'][4];
Now I'm pretty sure the above part is not right. So this is my question... How would I get the info from these inputs into my email that's sent since their created by an array and not "actually" there. Here's a stripped down version of my html email that's sent which I'm pretty sure is also wrong since the above code is incorrect:
<table>
<tr>
<td>Gross Sales:</td>
</tr>
<tr>
<td>{$year_brand_gross[1]}</td>
<td>{$year_brand_gross[2]}</td>
<td>{$year_brand_gross[3]}</td>
<td>{$year_brand_gross[4]}</td>
</tr>
</table>
Any help is greatly appreciated!
Your form would actually look like
<input type="number" name="year_brand_gross[2012]" ... />
<input type="number" name="year_brand_gross[2011]" ... />
<input type="number" name="year_brand_gross[2010]" ... />
etc...
That means you need to use
$_POST['year_brand_gross'][2012]
$_POST['year_brand_gross'][2011]
$_POST['year_brand_gross'][2010]
etc...
on the server.
foreach($_POST['year_brand_gross'] AS $yeah => $value) {
// use $year and $value variables to do whatever
// this code will execute once for each values in $_POST['year_brand_gross'].
// note: print_r($_POST);
// $_POST is an array, same for $_GET and so on
}
Related
I'm learning PHP and trying to understand the if .. else statements a little better, so I'm creating a little quiz. However, I have come across an issue and I don't seem to know what the issue is. My problem is that whenever I type in the age in the input area, it will give me the $yes variable every time even if I enter the wrong age.
Here is my code so far:
My html file:
<form action="questions.php" method="post">
<p>How old is Kenny?<input></input>
<input type="submit" name="age" value="Submit"/>
</p></form>
My php file:
<?php
$age = 25;
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25){
echo "$yes";
}else{
echo "$no";
}
?>
You catch the user input inside the $_POST superglobal var (because the method of your form is POST.
So
<?php
$age = 25;
should be
<?php
$age = $_POST['age'];
There is an error in HTML too. This
<input type="submit" name="age" value="Submit"/>
should be
<input type="text" name="age" value=""/>
<input type="submit" value="Click to submit"/>
Because you want one input and one button. So one html element for each element.
and <input></input> must be cleared because it's not valid syntax :-)
<form action="questions.php" method="post">
<p>How old is Kenny?</p><input type="text" name="age"></input>
<input type="submit" value="Submit"/>
</form>
$age = (int) $_POST["age"];
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25) {
echo $yes;
} else {
echo $no;
}
<?php
/* Test that the request is made via POST and that the age has been submitted too */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['age'] ) ){
/*
ensure the age is an integer rather than a string ..
though for this not overly important
*/
$age=intval( $_POST['age'] );
if( $age==25 ) echo "Congratulations";
else echo "Bad luck!";
}
?>
<form action="questions.php" method="post">
<p>How old is Kenny?
<input type='text' name='age' placeholder='eg: 16' />
<input type="submit" value="Submit" />
</p>
</form>
A simple html form, note that the submit button does not carry the values you want to process, they are supplied via the input text element.
First of all, you need to echo the variable; echoing "$no" will keep it as a string. Remove the quotes from "$no" and "$yes" in your if then statement. Otherwise, your code seems sound!
Currently I have 100 text input boxes named contact0 through contact101. I am trying to get the Post data and name each string to itself. Meaning $contact0 = $_POST['contact0'];all the way up to $contact101 = $_POST['contact101']; there has to be a simpler way to set them in a loop or something. Overall the end result is I just want the data entered in the textbox to become the value of the textbox when submitted. Any suggestions will help I might be doing this wrong for the results I want.
for ($i = 0; ;$i++){
if($i < 101){
$contact.$i = $_POST['contact'].$i;
echo $contact.$i;
}
else{
break;
}
}
for ($i = 0; $i <= 101; $i++){
${"contact".$i} = $_POST['contact'.$i];
echo ${"contact".$i};
}
You may want to consider amending your HTML form. Rather than create 100 new variables, you can assign all the contacts to an array and then reference them with the array index.
HTML
<input type="text" name="contacts[]" value="Contact 1 name"/>
<input type="text" name="contacts[]" value="Contact 2 name"/>
// etc...
PHP
$contacts = $_POST['contacts'];
var_dump($contacts);
// prints array(0 => 'Contact 1 Name', 1 => 'Contact 2 Name'...
As it now an array, you can reference the contact e.g. $contacts[34] and know it will be a valid entry.
EDIT
A working example:
<?php
if (isset($_POST['contacts'])) {
$contacts = $_POST['contacts'];
echo "<p>The contacts are below:</p>";
print_r($contacts);
} else {
echo "<p>Please enter the contacts</p>";
}
?>
<form method="post" action="">
<?php for($x = 0; $x < 100; $x++): ?>
<input type="text" name="contacts[]" value="<?php echo (isset($contacts[$x])) ? $contacts[0] : ''; ?>"/>
<?php endfor; ?>
<input type="submit" name="submit" value="submit"/>
</form>
Edit 2
I have now made the form a loop, meaning it will create all our contact inputs for us. On top of this, if we have already posted the form each field will have the correct contact values.
If you are not aware of the syntax, echo isset($contacts[$x])) ? $contacts[$x] : ''; is a ternary operator which is a one line if/else statement.
Which can also be tested here: http://phpfiddle.org/api/run/ugb-cta
i have a form in html that when the certain fields are clicked i want it to add up the values in the php part, so i thought that if i put the php part in the value area of the html then it would add it up, but it adds them all up but not the specific ones when clicked, Please help:
<p>
<input type="checkbox" name="one" value= <?php $number = 2.39; ?>
<label for="one">Four 100-watt light bulbs for $2.39</label>
<p>
$total = $number + $numberone + $numbertwo + $numberthree;
echo "Total cost is " .$total;
echo $card;
?>
</form>
First, you need to echo out the number value in your form, not just assign the variable, nothing will be rendered there. Also, I find that if you're adding numbers for totals, it's easier to name them in a fashion that you can pull the values back out in an array
name="one"
would become
name="price[]"
or something of the like.
<p>
<input type="checkbox" name="price[]" value= <?php echo('2.39'); ?>
<label for="one">Four 100-watt light bulbs for $2.39</label>
</p>
Then on the server side, just sum the totals
$total = 0;
foreach($_POST['price'] AS $value){
$total += $value;
}
You'll want to do some input sanitization, but this example should get you going.
This example will only work on the server-side after a form submission, if you want to add them up in realtime on the page, you'd have to use ajax to add the values up.
I am trying to create a "report" that can be filtered using a form on the top of the page. The options to filter the results is the Fiscal Year which is the current FY by default and multiple categories (check boxes) which are all checked by default. The page generates properly with the default data but when the form is submitted the page will "refresh" but there is no POST data generated. I tried creating a copy of the page and setting it as the action URL but it still did not have any POST data and used the defaults. I will include my code below and will try to narrow it down to just the necessary parts to make it easier but can share all of it if need be. Thank you in advance for any help offered.
<body>
<?php
if(isset($_POST['submit'])){echo"SET";} else{echo"NOT SET";}
// Establish Connection and Variables
// Connection
include "./include/class/DBConnection.php";
DBConnection::$dsn;
DBConnection::$user;
DBConnection::$pass;
DBConnection::getDBConnection();
// The Current Fiscal Year
$today = getdate();
$month = $today['month'];
// seperate first and second half of fiscal year
$old = array('January','February','March','April','May','June');
if (in_array($month,$old)) {
$year = $today['year'] + 1;
}
else {
$year = $today['year'];
}
// Create SQL Query Variables - Removed for post
// Set filter criteria
// Retrieve array of possible categories and create SQL WHERE statment
$catAllCxn = DBConnection::$cxn->prepare($SQL_Categories);
$catAllCxn->execute();
$catAllCxn->setFetchMode(PDO::FETCH_ASSOC);
$catAllArray = array();
while($catAllRow = $catAllCxn->fetch()) {
$cat = $catAllRow['Category'];
array_push($catAllArray, $cat);
}
$catAllInQuery = implode(',',array_fill(0,count($catAllArray),'?'));
// Create array for category filter IF form was submitted to itself
if (isset($_POST['submit'])){ // if page is submitted to itself
$catFilterArray = $_POST['Category'];
$catFilterInQuery = implode(',',array_fill(0,count($catFilterArray),'?'));
}
// Switch for ALL or Filtered report
if(!isset($_POST['submit'])) { // if page is not submitted to itself
$FiscalYear = $year;
// $DiscludedDepartmentNumbers = "21117";
$catArray = $catAllArray;
$IncludedCategories = $catAllInQuery;
}
else {
$FiscalYear = $_POST["FiscalYear"];
// $DiscludedDepartmentNumbers = "21117";
$catArray = $catFilterArray;
$IncludedCategories = $catFilterInQuery;
}
?>
<!-- Filter Form -->
<div id="filters" style="border: 1px solid;">
<form name="filter" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
Fiscal Year: <input type="text" name="FiscalYear" value="<?php echo $FiscalYear; ?>" /> <?php if(isset($_POST['submit'])){echo"SET";} else{echo"NOT SET";}?>
<br />
<fieldset>
<legend>Select Categories</legend>
<?php
foreach($catAllArray as $catAllRow) {
if (!isset($_POST['submit'])) {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" checked=\"checked\" />".$catAllRow." \n";
}
else if(in_array($catAllRow,$catArray)) {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" checked=\"checked\" />".$catAllRow." \n";
}
else {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" />".$catAllRow." \n";
}
}
?>
</fieldset> <br />
<input type="submit" value="submit" />
</form> <!-- End: filter -->
</div> <!-- End: filters -->
From here the original code continues to output results into a table but this works properly and I don't think it is the problem. I can share more if asked.
You need to give the submit button a name, if that's what you're using to check if the form is submitted...
<input type="submit" value="submit" name="submit" />
Or if you dont want to change the submit button, you can check isset on the category input instead
if(isset($_POST['Category'])){echo"SET";} else{echo"NOT SET";}
I think that your check if there is a _POST value is wrong. try this:
if(isset($_POST['FiscalYear']))
And see if that works
you need to name your submit button if you want to check for it
<input type="submit" value="submit" name="submit" />
otherwise php will not place it in the $_POST array
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
How to loop through dynamic form inputs and insert into an array
I have a php script and a form. The php script makes an xml file but what i need is for someone to enter a number and that would set that amount of textboxes that would be for someone to write data for that xml file.
So i need it to write <input type="text" name="a #"> however many times the user enters. Also the name needs to be a number but it counts by one ex:<input type="text" name="1"> <input type="text" name="2">... Thanks
<?php
session_start();
if(isset($_POST['quantity']){
// code here to check isnum and min/max
$count = $_POST['quantity'];
for ($i=1; $i<=$count; $i++){
#$s.= "<input type=text name=".$i."><br>";
}
?>
now just echo out $s in your html
This?
<form method="get" action="">
<div><input type="text" name="num_inputs" value="1" placeholder="Number of inputs"/></div>
</form>
<?php $num_inputs = isset($_GET['num_inputs']) ? $_GET['num_inputs'] : 1; ?>
<form method="post" action="">
<?php for ($i = 0; $i < $num_inputs; $i++) : ?>
<div><input type="text" name="inputs[]"/></div>
<?php endfor ?>
</form>
Edit: yes, an array is much better than input_x. Updated my answer.
I think what you want is an array of form fields.
You want something like this:
<?php
$number_of_textboxes = 5; // you'd get this from a $_GET parameter
echo str_repeat('<input type="text" name="mybox[]" />', $number_of_textboxes);
?>
This will print five text boxes:
<input type="text" name="mybox[]" />
Then, when you reference these boxes' values, you do so like thus:
<?php
foreach ($_POST['mybox'] as $i) {
echo $i;
}
?>
That is, by using "mybox[]" as the name of each input field, you create an array of textboxes, which you can then iterate through.