I have a form that has radio inputs that have a dynamically generated name like below:
<input type="number" name="<?php echo date("Y")-4 ?>brand%gross" placeholder="Gross Sales % for <?php echo date("Y")-4 ?>">
<input type="number" name="<?php echo date("Y")-3 ?>brand%gross" placeholder="Gross Sales % for <?php echo date("Y")-3 ?>">
<input type="number" name="<?php echo date("Y")-2 ?>brand%gross" placeholder="Gross Sales % for <?php echo date("Y")-2 ?>">
<input type="number" name="<?php echo date("Y")-1 ?>brand%gross" placeholder="Gross Sales % for <?php echo date("Y")-1 ?>">
Then the form is processed and creates a dynamic table with all the values the user inputs that is then emailed to me. My question is how do I get dynamically generated radios to output to the table that is sent? I know the below isn't correct but just to give you a better look at what I'm trying to do:
if( isset($_POST) ){
${ echo date("Y")-4 } = $_POST['{ echo date("Y")-4 }];
Any help is greatly appreciated!
If you want to set a varible content inside $_POST, well... Use a variable.
$foo = date("Y")-4;
$_POST['str'] = $foo;
So... the thing is , you want to use a variable variable name that might go like this:
$foo = date("Y")-4;
$$foo = $_POST[$foo];
Got it?
EDIT 1:
So that the variable won't start with a number:
$bar = "dt_";
$foo = date("Y")-4;
${$bar.$foo} = $_POST[$foo];
By have a string (the output of date()) from which you subtract and integer, you end up casting the result as an integer, not a string. You are probably better off making the string correctly to begin with and getting rid of the integer arithmetic issue.
I would suggest working with DateTime objects. Here's how you might output you input fields.
<?php
$current_date = new DateTime();
while($i = 1; $i <= 4; $i++) {
$date_int = new DateInterval('P' . (string)$i . 'Y');
$temp_date = $current_date->sub($date_int);
$date_string = $temp_date->format('Y');
?>
<input type="number" name="<?php echo $date_string; ?>brand%gross" placeholder="Gross Sales % for <?php echo $date_string; ?>" />
<?php
} // end while
?>
When processing the $_POST you can do similar:
<?php
$current_date = new DateTime();
$year_array = array();
while($i = 1; $i <= 4; $i++) {
$date_int = new DateInterval('P' . (string)$i . 'Y');
$temp_date = $current_date->sub($date_int);
$date_string = $temp_date->format('Y');
if (!empty($_POST[$date_string. 'brand%gross'])) {
$year_array[$date_string] = $_POST[$date_string . 'brand%gross'];
}
} // end while
?>
Note that I use an array to store your data indexed by year string , as you can't have a variable name that starts with a number (i.e. $2013nrand%gross is not valid).
I would also STRONGLY suggest using array access notation in your inputs to simply things.
If you made each input like this:
<input type="number" name="year_brand_gross[<?php echo $date_string; ?>]" placeholder="Gross Sales % for <?php echo $date_string; ?>" />
Then the names of year_brand_gross[2013] and such would automatically get populated as an array into $_POST['year_brand_gross'], eliminating the need to loop through the POST input.
Instead you could set this to a variable like this
if(!empty($_POST['year_brand_gross']) {
$year_array = $_POST['year_brand_gross'];
}
For PHP < 5.3.0 you can use alternate method to generate the year strings:
$current_date = new DateTime();
for ($i = 1; $i <=4; $i++) {
$current_date->modify('-1 year');
$date_string = $current_date->format('Y');
// other code here
}
Note that, as shown, this will alter the value of $current_date with each iteratoin, which differs from the first solution.
First off you want to update you html so that the names of the fields
<input type="number" name="year[<?= date("Y")-4 ?>brand%gross]" placeholder="Gross Sales % for <?= date("Y")-4 ?>">
<input type="number" name="year[<?= date("Y")-3 ?>brand%gross]" placeholder="Gross Sales % for <?= date("Y")-3 ?>">
<input type="number" name="year[<?= date("Y")-2 ?>brand%gross]" placeholder="Gross Sales % for <?= date("Y")-2 ?>">
<input type="number" name="year[<?= date("Y")-1 ?>brand%gross]" placeholder="Gross Sales % for <?= date("Y")-1 ?>">
In your PHP you will be able to access the elements by there keys
$val2010 = $_POST["year"]["2010brand%gross"];
Related
I have here a looped value of checkboxes let's assume I have 3 increments
<?php foreach ($times as $time) { ?>
<input type="checkbox" name="b" id="b1" value=" <?php echo $time->format('h:i a'), '-', $time->add($interval)->format('h:i a'); ?>">
<?php } ?>
In the foreach it display 3 checkboxes that has different value.
Now for example i checked 2 boxes. The query must run twice? Or better yet, the 2 checked value must be inserted to the db.
$b = $_POST['b'];
$ins = mysql_query("INSERT INTO ehr_schedule3(`sched3_time) VALUES('$b')");
How can I do that?
All your checkboxes have the same name, so $_POST['b'] will just get the value of the last one. To get multiple values, you need to use an array-style name:
<?php foreach ($times as $time) { ?>
<input type="checkbox" name="b[]" value="<?php echo $time->format('h:i a'), '-', $time->add($interval)->format('h:i a'); ?>">
<?php } ?>
Then $_POST['b'] will be an array of all the values.
foreach ($_POST['b'] as $b) {
$b = mysql_real_escape_string($b);
$ins = mysql_query("INSERT INTO ehr_schedule3(`sched3_time) VALUES('$b')");
}
I also took out id="b1" because you shouldn't have multiple elements with the same ID. If you really need the inputs to have IDs (why?), you'll need to give them different ones, perhaps by using the array index as part of the ID.
You can put a counter to count bs:
<?php
$count = 0;//to count the rows if they are dynamic
foreach ($times as $time) {
?>
<input type="checkbox" name="b<?php echo $count; ?>" value="<?php echo $time->format('h:i a'), '-', $time->add($interval)->format('h:i a'); ?>">
<?php
$count++;
}
?>
<input name="rowCount" type="hidden" value="<?php echo $count; ?>" /><!-- to store number of inputs -->
then in your insert function
$b_count = $_POST['rowCount'];//to store count of b
$my_quries = [];
for($i=0; $i<$b_count; $++){
$b = $_POST['b'.$i];//get the corresponded b from POST req
$my_quries[] = mysql_query("INSERT INTO ehr_schedule3(`sched3_time) VALUES('$b')");
//you can execute the query in this loop or another one as you like
}
I want to create limit input tag with php for loop an get inputs values. My sample code is this:
<?php
$limit = 10;
for ($i=1; $i<=$limit; $i++) { ?>
<input name="<?php echo $i ?>" type="text" /><br>
<?php } ?>
Is my code correct? How can I get input values?
You can try my script.
<?php
$limit = 10;
?>
<form method="post">
<?php
for ($i = 1; $i <= $limit; $i++) {
?>
<input name="anything[]" type="text" /><br>
<?php } ?>
<input type="hidden" name="op" value="sent" />
<input type="submit" value="submit" />
</form>
<?php
if (!empty($_POST["op"])) {
for ($i = 1; $i <= $limit; $i++) {
if (strlen($_POST["anything"][$i]) !== 0) {
?>
<p>The value of the <?php echo $i; ?> text field is: <?php echo $_POST["anything"][$i]; ?>
<?php
} else {
?>
<p><?php echo $i; ?> was not set.</p>
<?php
}
}
}
Looks alright but I would use an array as the input name. For example:
<?php
$limit = 10;
for ($i=1; $i<=$limit; $i++) {
?>
<input name="number[<?php echo $i; ?>]" type="text" /><br>
<?php
}
?>
That way in the back end you can just loop through the number array like so.
foreach ($_POST['number'] as $key => $value) {
// Do stuff
}
Your code should render 10 html input fields with name 1, 2, 3, ... 10 correctly
To get input values, wrap your input fields in a form element with an action pointing to the php script in which you want to read the values (e.g. action="myscript.php").
(You should add a input type="submit" to have a way to submit the form. I assume you know HTML good enough to create a simple form.)
The script invoked by submitting the form (e.g. myscript.php) will now be able to read the values using the $_GET array. See http://php.net/manual/de/reserved.variables.get.php
You could print the values like so:
<?php
for($i=1;$i<=10; $i++) {
echo $i . ' : '. $_GET[$i];
}
?>
Edit: As #David Jones mentioned it would be better to use an array as input name
I do a form, inside I would like to do a loop for to show the same field. Each field will have different value and I would like to use sessions to take all the value.
Here is my code:
for ($i = 1; $i <= 5; $i++) { //normally not 5 but a random number, choose by user
echo "Numero ";
echo $i;
?>
<input type="text" name="number2" id="number2"/>
<?php
}
?>
</form>
<?php
echo $_POST['number2'];
$my_array=array($_POST['number2']);
$_SESSION['countnumb']=$my_array;
in another page:
foreach($_SESSION['countnumb'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
I can't register any number. How can I do this? thanks
Basics First - ids should be unique in a webpage.
Declaring <input type="text" name="number2" id="number2"/> in a loop is wrong.
For creating multiple input using loop try like this-
echo "<input type='text' name='number[$i]' id='number{$i}' />";
<input type="text" name="number[2]" id="number2"/>
would make $_POST['number'] an array which you can loop though server side, This is described here http://www.php.net/manual/en/faq.html.php#faq.html.arrays
foreach ($_POST['number'] as $number){
echo $number;
}
for example
this would make your code
for ($i = 1; $i <= 5; $i++) { //normally not 5 but a random number, choose by user
echo "<input type="text" name="number[$i]" id="number{$i}"/> ";
?>
<?php
}
?>
</form>
<?php
print_r( $_POST['number'] );
$_SESSION['countnumb']= $_POST['number'];
I am developing an ordering page in PHP for some products. The user needs to be able to select multiple types of products, so checkboxes will be necessary in the HTML form.
I've established an array for the checkboxes via the "name" attribute.
My problem is, I want to display what the user has selected on a confirmation page, so I'd like the "value" of those checkboxes to ultimately return a product name AND a product price. As far as I can tell I'm going to be stuck with one value only, so I've attempted to get around this:
<?php
//variables for the array and the count
$parray = $_POST['product'];
$pcount = count($parray);
//arrays for each product's information; i've only listed one for simplicity
$br = array("Big Red", 575);
/*The idea for this was for each product ordered to add a line giving the product information and display it. When the $key variable is assigned, it is stored simply as a string, and not an array (yielding [0] as the first letter of the string and [1] as the second), which I expected, but my general idea is to somehow use $key to reference the above product information array, so that it can be displayed here*/
if (!empty($parray))
{
for ($i=0; $i < $pcount; $i++)
{
$key = $parray[i];
echo "<tr><td height='40'></td><td>" . $key[0] . "</td><td>" . $key[1] . "</td></tr>";
}
}
?>
Is there anyway to make my $key variable actually act as if it is the array's name it is set to?
If not, is there any good way to do this?
So in your HTML table, you'll need to render each checkbox like this:
<input type="checkbox" name="selectedIDs[]" value="$key" />
where $key is the item number.
Then, in your PHP, you'll have a $_POST["selectedIDs"] variable, which is an array of all the item numbers that were checked.
Assuming you've got a product list array like this:
$products = array( 1 => array("Big Red", 575), 2 => array("Spearmint", 525));
You can then print a list of the selected products using a loop like this:
for($i = 0; $i < count($_POST["selectedIDs"]); $i++) {
$key = $_POST["selectedIDs"][$i];
$product = $products[$key];
echo "<tr><td height='40'></td><td>" . $product[0] . "</td><td>" . $product[1] . "</td></tr>";
}
The only real difference between this and what you wrote is that my $products array is two-dimensional, and my $key is used to grab the relevant product from the $products array.
You can give the value of the options the value of the ID of the corresponding item. Then you'll receive an array of ID's, which you can then again map to the $br array, where you look up the name and price of an item by its ID. You could use the array key as ID, so:
<!-- Form: -->
<input type="checkbox" name="product[]" value="1" />
<input type="checkbox" name="product[]" value="..." />
<input type="checkbox" name="product[]" value="15" />
[...]
<?php
$product = array();
$product[1] = array('name' => "Big Red", 'price' => 575);
$product[...] = array('name' => "...", 'price' => ...);
$product[15] = array('name' => "Small Green", 'price' => 475);
foreach ($_POST['product'] as $pId)
{
echo $products[$pId]['name'] . " costs " . $products[$pId]['price'];
}
?>
If of course your array originates from a database, you can use the table's ID's as values for the checkboxes. You could then implode the $_POST['product'] (of course after escaping it) with a comma, and use it in a SELECT ... WHERE ID IN ($productIds) query.
If i'm understanding you correctly, you'll have checkboxes something like this:
<input type="checkbox" name="product_id[]" value="1">Product #1<br/>
<input type="checkbox" name="product_id[]" value="2">Product #2<br/>
<input type="checkbox" name="product_id[]" value="3">Product #3<br/>
That should post whatever is checked as an array to your server.
gen_paper1.php
<div style="overflow: auto; height: 500px; border: 1px solid;">
<form action="" method="post">
<fieldset style="font-size: 15px; font-weight: bolder;">
<h4><u>Your Existing Header's are listed below</u> </h4>
<hr / >
<?php
$xhdr = mysql_query("SELECT * from s_user_header ORDER BY 'ASC'");
while($rheader = mysql_fetch_array($xhdr)){
$h = $rheader['h_content'];
$hid = $rheader['h_id'];?>
<script>
$(document).ready(function(){
//$('input[type=checkbox]').val('<?php echo $hid ; ?>').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
//$('#c').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
$('').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
});
</script>
<table>
<td><input type="checkbox" id="c" name="u_hdr[]" value="<?php echo $hid; ?>"></td>
<td style="font-weight: bolder"><?php echo $h."<br />"; ?></td>
</table>
<?php } ?>
</fieldset>
</div>
gen_paper2.....3.....
i need all this values in further page, so have taken hidden variables
<input type="hidden" name="hstdid" value="<?php echo $stdid; ?>">
<input type="hidden" name="hsubid" value="<?php echo $subid; ?>">
<input type="hidden" name="hdifid" value="<?php echo $difid; ?>">
<input type="hidden" name="hmarks" value="<?php echo $t_marks; ?>">
<input type="hidden" name="h_hid[]" value="<?php echo $hh; ?>">
gen_paper4.php
$getstdid = $_POST['hstdid3'] ;
$getsubid = $_POST['hsubid3'] ;
$getdifid = $_POST['hdifid3'] ;
$gethmarks = $_POST['htmarks'] ;
$hdr= $_POST['h_hdrid'] ;
$h = implode($hdr);
<table>
<?php
$h1 = explode(",",$h);
count($h1) . "<br />";
for($i=0;$i<count($h1);$i++){
$h1[$i];
$xheader = mysql_query("SELECT * from s_user_header WHERE h_id = ".$h1[$i]);
while($row = mysql_fetch_array($xheader)){ ?>
<tr>
<td><b>
<?php echo $i + 1 . ".   "; ?>
</b></td><td>
<?php echo $header = $row['h_content'] . "<br />";
?></td>
</tr>
<?php
}
}
//echo $header; ?>
</table>
I am quite new to php. Can somebody please guide me what is wrong with the code.
<?php
if(!isset($_POST['submit']) || $_POST['submit']!="calculate")
{
$_POST['Contrib']="";
$_POST['Currentage']="";
$_POST['Retireage']="";
$Total =0;
$AnnGain =7;
}else{
$AnnGain = $_POST['AnnGain'];
$Years = $_POST['Retireage'] - $_POST['Currentage'];
$YearCount = 0;
$Total = $_POST['Contrib'];
while ($YearCount < $Years)
{
$Total = (round($Total) *(1.0 + $AnnGain/100) +
$_POST['Contrib']);
$YearCount = $YearCount+1;
}
}
?>
<b>A Retirement Saving calculator</b>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<p> Your age now
<input type="text" size = "5" name = "Currentage"
value="<?php echo $_POST['Currentage'];?>">
<p> The age at which you want to retire
<Input type="text" SIZE="6" name="Retireage"
value="<?php echo $_POST['Retireage']; ?>">
<p> Annual Contribution
<input type="text" size = "15" name = "Contrib"
value="<?php echo $_POST['Contrib'];?>">
<p>Annual Return
<input type = "text" size = "5" NAME = "AnnGain"
value="<?php echo$AnnGain; ?>">
<BR><BR>
<p><b>Nest Egg </b>: <?php echo $Total; ?>
<p><Input type = "submit" Name = "submit" value = "calculate">
</form>
In your code i see:
input type="test"
It is wrong, it should be:
input type="text"
Input type should be text if you mean a textbox.
$_POST['Currentage']=="";
$_POST['Retireage']=="";
You're checking if $_POST['Currentage'] is equal to "" instead of setting it to "". What you want is $_POST['Currentage'] = "";. You have the same problem with $_POST['Retireage'].
outside of the fact that modifying $_POST variables is bad practice (just assign those values to a variable and use that in your code)
$_POST['Currentage']==""; should be $_POST['Currentage'] = '';
$_POST['Retireage']==""; should be $_POST['Retireage'] = '';
ALWAYS escape data using something like htmlentities() before you spit it out to the web browser to protect your page from injections. This is VERY important