I'm trying to write a web application in which students enter their timetable. For example: First period of Monday is math, second period of Monday is English,... first period of Tuesday is history, second period of Tuesday is biology,... etc.
So I write a form like this:
<form method="post" action="timetable_handling.php">
<?php
for ($period=1;$period<=9;$period++)
{
echo "<tr>";
for ($day=1;$day<=7;$day++)
{
echo "<td><input name="the_subject_of_the_nth_$period_on_$day" type="text"></td></tr>";
//the problem is here
}
}
?>
</form>
So my question is, are there any ways to pass the many variables to another php file to handle without having to manually write its name explicitly?
Edit 1: I mean is there anyway to encode the period and day information in the name, so that when it sends to timetable_handling.php I can just loop through it to save it into sql database. Something like an array $subject[day][period].
I would be grateful if someone could help me.
Start with the following on your timetable data entry page:
<form method="post" action="timetable_handling.php">
<table>
<?php
for ($period=1; $period<=9; $period++)
{
echo '<tr>';
for ($day=1; $day<=7; $day++)
{
echo '<td><input name="subject_of_period_'.$period.'_on_day_'.$day.'" type="text"></td>';
//the problem is here
}
echo '</tr>';
}
?>
</table>
<input type="submit" value="Submit Form" />
</form>
Then follow up with this script on your timetable_handling.php:
<?php
for ($day=1; $day<=7; $day++)
{
for ($period=1; $period<=9; $period++ )
{
${'subject_of_period_'.$period.'_on_day_'.$day} = htmlspecialchars($_POST['subject_of_period_'.$period.'_on_day_'.$day],ENT_QUOTES);
echo '<p>Subject of Period '.$period.' on Day '.$day.' is '.${'subject_of_period_'.$period.'_on_day_'.$day}.'</p>';
}
}
?>
It's secure and it works.
Yes. If you format a variable name something like
for ($day=1;$day<=7;$day++)
{ ?>
<td><input name="subject['<?= $period ?>'][<?= $day ?>]" type="text"></td></tr>
//the problem is here
<?php }
PHP will turn $_POST['subject'] into a 2D array for you. (Note I make no promise this is free of syntax errors.)
In the form handler you can loop through all the posted fields like this:
foreach($_POST as $field => $value)
{
}
Where $field would be the input-tag name and $value it's value.
If you have other form elements you can check which ones you need with some kind of prefix, like if the fieldname starts with 'the_subject', you know it's one of the fields that were dynamically added.
sure, you already did part of the answer :)
first issue: you are not escaping your string properly:
Here is 1 another way
echo '<td><input name="'.$period.'_on_'.$day.'" type="text"></td></tr>';
As for handling the post here is what you can do. You might need to tweak it around to get the exact desired result. But you are talking about multidimentional array.
if (isset($_POST)){
$something=array();
foreach ($_POST as $single=>$value)
{
array_push($something, array('period_'.substr($single,0,1) => array('day_'.substr($single,-1)=>$value)));
}
}
echo '<pre>'.print_r($something,true).'</pre>';
Good Luck.
Related
I would like to have a form that enables a user to choose the vehicles. The user should get the total price of his choice. I wrote this little script, and it works properly. I am just curious is there a better way to do it. For example, there are a lot of IFs in foreach loop. What if I have, for instance, 100 checkboxes. Should I automate that in a way that for every new type of vehicle the script should make new IF statement? That sounds awkward. Is there a way to put a number of prices directly in checkbox form or something? However, what would be the best way to do such a thing. Thanx.
if (isset($_POST['submit'])){
$automobils=$_POST['auto'];
$set= array();
echo "You ordered: " ;
foreach ($automobils as $model){
if ($model == "chevrolet"){
$set[]=20000;
}
if ($model == "reno"){
$set[]=15000;
}
if ($model == "punto"){
$set[]=10000;
}
echo "<i>$model </i>";
}
$sum = array_sum($set);
echo "</br> Whole price is $sum $";
}
?>
<form action="" method="post">
<input type="checkbox" name="auto[]" value="chevrolet"/> Chevrolet</br>
<input type="checkbox" name="auto[]" value="reno"/> Reno</br>
<input type="checkbox" name="auto[]" value="punto"/> Punto</br>
<input type="submit" name="submit" value="Submit"/>
</form>
Well without adding a database and a whole another level of fun programming.
You can do this with an explode command (And really shrinks your foreach as well)
on the input value
value="chevrolet"
Change to something like
value="chevrolet;20000"
then in your foreach loop
foreach ($automobils as $model){
$eachmodel = explode(";",$model);
$set[] = $eachmodel[1];
}
Ideally you'd store your possible values, and their corresponding prices, in a database, rather than in your code. But here's a quick solution, involving an associative array acting as a map between each vehicle and its price.
$map = [
'chevrolet' => 20000,
'reno' => 15000,
'punto' => 10000
];
if (!empty($_POST['auto']) {
echo 'You ordered:<br />';
$total = 0;
foreach($_POST['auto'] as $model)
if (array_key_exists($model, $map)) {
echo ' - '.$model.'<br />';
$total += $map[$model];
}
echo 'Total price: '.$total.'<br />';
}
Then, you just update the map as you add/change vehicles/prices etc.
Note it's key to store the allowed values/prices code-side (or in a DB) rather than in your form as the latter is editable via the DOM, so you'd need something server-side to validate it anyway.
If you want to put number in checkbox. You can put it with value by using some special separator.
For example
<input type="checkbox" name="auto[]" value="punto_20000"/> Punto</br>
Later you can use Explode string and can get value for selected.
I'm creating a form from a database and the input id's could be 1-9, 1,2,5,8, etc. IE with the way it is now, I cannot determine what the number will be unless I were to iterate from number 1 to the final number of menu items in the database... which I imagine is not optimal from a coding perspective.
I have two files. File1 will get list number of menu items from a database and create a list. The condensed version of my code is as follows, please keep in mind i have condensed a lot of useless stuff;
File1.php
$menuArray = openMenu(1);
$return = "<div id='menu'><form method='post' action='file2.php'><input type='submit' name='submit' value='Commit Order' /><table class='tableinfo'>";
$i=1;
foreach($menuArray as $recordNum => $record)
{
if ($record['available'] > 0)
{
$thisClass='available';
} else{
$thisClass='unavailable';
}
$return.="<tr class='$thisClass'>
<td>$record[itemid]</td>
<td><label for='$record[itemid]'>$record[name]</label></td>
<td><button type='button' id='itemid-$record[itemid]' class='subtract'>-</button><input class='itemadder' id='itemid-$record[itemid]' type='number' min='0' value='0' /><button id='itemid-$record[itemid]' class='addition' type='button'>+</button></td>
</tr>";
}
$return.="</table></form></div>";
return $return;
File2.php
I don't know how to code this :(
Is anyone able to shed some light on the best way to do this?
I just need a way to be able to see what id's have a value when posted.
I am using jQuery at the moment; would this be something best done using jquery?
Assuming I understand you correctly the best way to do this would be to have an array of inputs.
Code you should try to achieve for your HTML output would need to be something like this:
<input type="text" name="number[1]" value="" />
<input type="text" name="number[3]" value="" />
<input type="text" name="number[5]" value="" />
Now you know after your form submission in PHP:
foreach($_POST['number'] as $id => $value){
echo 'The value for ID #' . $id . ' is ' . $value;
}
The script File1.php rendering the inputs above does know about what has rendered out. So what, if it also puts a list of rendered form element names in to the session for later use in file2.php:
In the beginning:
$_SESSION['formids'] = array();
in the loop:
....
$_SESSION['formids'][] = "itemid-" . $record[itemid];
and in file2.php:
$sendItems = $_SESSION['formids'];
...
foreach ( $sendItems as $itemId )
{
$val = empty($_POST[$itemId]) ? null : $_POST[$itemId];
if ( isset($val) )
...
This is going to be a bit difficult to explain but I will try my best to explain it as good as i can.
I am passing Data from an input textfield on one page (page1.php) to a Select form on another page (page2.php).
This works as should.
the Select Form contains some PHP timezones and when a timezone is selected, the page page will echo the current time for that timezone.
This also works as it should.
The problem is when I enter a timezone name in the input textfield on (page1.php) , it will show the name in the Select Form on (page2.php) BUT it will not echo its current time and it will throw out this error:
Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::__construct(): Unknown or bad timezone (London)' in page2.php:16 Stack trace: #0 on line 16.
when infact the timezone London exists in the Select Form Options and if I enter/search for London directly in the select form, it will echo the current time for that timezone but it will NOT if the timezone name was entered in the input textfield on page1.php and it was passed to the select form on page2.php!
here is what I have on page2.php:
<?php
if( isset($_POST['submit']))
{
//be sure to validate and clean your variables
$timezone2 = htmlentities($_POST['timezone2']);
//then you can use them in a PHP function.
function get_timezone_offset( $remote_tz ) {
$timezone2 = new DateTimeZone ( $remote_tz ); ----->>> Line 16 is here.
$datetime2 = new DateTime ("now", $timezone2);
$offset = $timezone2->getOffset($datetime2);
return $offset;
}
$offset = get_timezone_offset($timezone2);
}
?>
<?php
$options = array();
$options[$_POST["location"]] = $_POST["location"]; <<<<<<----- Data from input textfield on page1.php
$options["Africa/Addis_Ababa"] = "Addis Ababa"; <<<<<<----- Select Form Options
$options["Europe/London"] = "London"; <<<<<<----- Select Form Options
?>
and here is the Select Form on page2.php
<form id="myForm" name="myForm" class="myForm" method="post" action="page2.php">
<select style="font-size:9px;" name="timezone2" id="timezone2" class="timezone2">
<?php
foreach($options as $key => $value)
{
echo '<option value="'. $key .'" label="'. $value .'">'.$value.'</option>';
}
?>
<option value="<?php echo $_POST["location"]; ?>"><?php echo $_POST["location"]; ?></option>
</select>
</div>
<div id="myBtn" style="position:relative; float:left; width: 228px; margin-top:50px; margin-left:350px;"><input type="submit" name="submit" id="submit" class="submit" value="Search"/></div>
</form>
and here is the input textfield on page1.php
<form method="post" action="../page2.php">
<input name="location" type="text" value="Search"/>
<button type="submit">Search</button>
</form>
could someone please point me in the right direction?
You're going about this wrong for a few reasons. Firstly, the list of possible timezones is finite so get rid of the text field and just use a dropdown.
Second, you can remove\rename the items in the dropdown all you want but just remember that since you are saving the offset and not the tz name you can never go back (my example will show you exactly why that is if you play with it). Usually, it is best to store the name and not the offset so that you can manage daylight savings properly. You'll notice that to get this system to work I need to call date('I') to find out if it is daylight savings which is really bad (just because it's daylight saving in my server TZ doesn't mean it is in the users TZ). If you saved the TZ name instead you could defer that logic to PHP and just use whatever offset it currently is. This may not seem important in this simplistic example but if you ever tried to store that offset or calculate future\past times using it you'll definitely have troubles.
One other tiny thing is that it is odd to put function definitions inside of 'if' statements. In PHP all function definitions are global so it will be available regardless of whether the 'if' condition is true. The problem with doing that is now you've obscured your logic with no gain. It is easier and clearer to put that elsewhere.
I've rewritten your code to be a little nicer and to actually work as you are using it but I've left out a few details (like aliasing the TZ names [which you seem to have a handle on how to do] and switching to using TZ names instead of offsets [because that may break other code you have]) but I encourage you to fix those as well.
<?php
$tz_offset=0;
function get_offset_time($offset=0) {
$original=new DateTime("now");
$timezoneName=timezone_name_from_abbr("", $offset, date('I'));
if(!$timezoneName) die('ERROR: Unknown timezone \''.($offset/3600).'\'');
$oTZ=new DateTimezone($timezoneName);
$modified = $original->setTimezone($oTZ);
return $modified->format('Y-m-d H:i:s');
}
function get_timezone_offset($tz_name=null) {
if(!$tz_name) return 0; // If we have invalid data then return before we error
$tz=new DateTimeZone($tz_name);
$dt=new DateTime("now", $tz);
return $tz->getOffset($dt);
}
function enumerate_tz($tz_select=null) {
global $tz_offset;
$tz_ident=DateTimeZone::listIdentifiers();
foreach($tz_ident as $val) {
$tmp_offset=get_timezone_offset($val);
if($val=='UTC'||$tmp_offset)
echo '<option value="'.$val.'" '. ($tmp_offset==$tz_offset?' selected':''). '>'.
$val. ' [ '.($tmp_offset/3600).' ]'. // If you'd like to customize the viewable names for each TZ you may do so here
'</option>';
}
}
if(isset($_POST['tz_input']) && $_POST['tz_input']) {
$tz_input=htmlentities($_POST['tz_input']);
$tz_offset=get_timezone_offset($tz_input);
}
echo '<html><title>Timezone Select</title><body>'.
'<p>The current timezone offset is: '. ($tz_offset? ($tz_offset/3600): '0'). '</p>';
echo '<p>The current time is: '. get_offset_time($tz_offset). '</p>';
echo '<form method=post><select name=tz_input>';
enumerate_tz($tz_offset); // You'll notice that this list duplicates many of the timezones so that after selecting one the next
// time through it'll often select a different one. If you want to fix that you'll need to save the actually offset name instead of an offset.
echo '</select><input type=submit value=Search />'.
'</form></body>';
?>
EDIT: One other thing to note is that PHP's timezone_name_from_abbr() function is not complete. Some timezone offsets will not return a TimeZone name. You must account for that as well. For example, even though PHP understands the 'Pacific/Midway' timezone it cannot find it when doing a reverse lookup. I've updated the code so that won't cause a hard error anymore.
EDIT2: I can see that you aren't going to be happy until someone shows you how to shine that turd. Here you go:
function getOptionDX($val, $option_array) {
if(!isset($option_array)||!is_array($option_array)||!count($option_array)>0||!$val) return null;
$val=htmlentities($val);
if(isset($option_array[$val])) return $val;
$new_val=array_search($val, $option_array);
return $new_val!==FALSE?$new_val: null;
}
Add this to your code and replace the call to htmlentities with a call to this:
$timezone2 = getOptionDX($_POST['timezone2'], $options);
Lastly, change this line:
if($timezone2) $offset = get_timezone_offset($timezone2);
If the user enters the TZ manually and it is correct then skip page2.php. This is as close to an answer as can be given if you don't want to change anything. The fact is that your logic is flawed in the first place (that is not meant to be a jab but it is true).
EDIT3: IDK what was wrong but here is my full code listing with the fixes you asked for:
<?php
$offset=0; $timezone2='';
$options = array();
$options["Africa/Addis_Ababa"] = "Addis Ababa";
$options["Europe/London"] = "London";
$options["America/Chicago"] = "The Windy City";
function getOptionDX($val, $option_array) {
if(!isset($option_array)||!is_array($option_array)||!count($option_array)>0||!$val) return null;
$val=htmlentities(ucwords(strtolower($val)));
if(isset($option_array[$val])) return $val;
$new_val=array_search($val, $option_array);
return $new_val!==FALSE?$new_val: null;
}
function get_timezone_offset( $remote_tz ) {
$timezone2=new DateTimeZone($remote_tz);
$datetime2=new DateTime("now", $timezone2);
$offset=$timezone2->getOffset($datetime2);
return $offset;
}
if(isset($_POST['location'])) {
$addLoc=getOptionDX($_POST['location'], $options);
if(isset($addLoc)) $options[$addLoc]=$_POST['location'];
else header('Location: '. $_SERVER['SCRIPT_NAME']);
}
if(isset($_POST['timezone2'])) {
$timezone2=htmlentities($_POST['timezone2']);
$offset=get_timezone_offset($timezone2);
}
if(isset($_GET['page2'])) {
?>
<form method=post action=?page2>
<select name=timezone2>
<?php foreach($options as $key=>$value) echo "\t".'<option value="'. $key .'"'.(get_timezone_offset($key)==$offset?' selected':'').'>'.$value.'</option>'."\n"; ?>
</select>
<input type=hidden name=location type="text" value="<?php echo $_POST['location']; ?>"/>
</div>
<input type=submit value=Search>
</form>
<p>Current Offset: <?php echo $offset/3600; ?></p>
<p>Current Time: <?php echo gmdate('Y-m-d H:i:s'); ?> UTC</p>
<p>Current Time: <?php echo gmdate('Y-m-d H:i:s', time()+$offset).' '. $timezone2; ?> </p>
<?php
} else {
?>
<form method=post action=?page2>
<input name=location type=text value=""/>
<button type=submit>Search</button>
</form>
<?php
}
?>
I've tested this and know it works, if that isn't enough to answer your question then I give up. I'm starting to think that you really want a way to invent new timezones which don't exist. That isn't possible. You can alias those which already exists as I've done here which is as close as you're ever going to get. Logically, time zones can only range from -12:00 to +12:00 and nearly every known timezone is already accounted for so you really have no choice but to rethink your design if this isn't enough.
I've really been racking my brain with this. I'll try to explain it to the best of my ability. It is mainly a data entry form.
First, there are three variables to start with. One is an array of regions (NYC, DC, etc) and the other to is a starting date (ex: 01/01/2012) and an ending date (ex: 1/15/2012)
In previous pages, the user selected the number of regions, selected the starting date to start recording, and the ending date. The intent is to enter 'points' and the dates are basically by week.
This is what the form is supposed to look like: http://i.imgur.com/9XflP2Z.png
In the boxes aside from the first column and first row, they are all input boxes. So, each input box is associated with the value at each end of the table (for example, the box next to NYC and under 01/01/2012 would enter data for NYC in the date range from 01/01/2012 to 01/08/2012).
My question is: How do I go about building this? Should I use a big 2d array? How would the submit button know which input boxes correspond to which date/region? My initial thought is maybe a hidden value that's like $array[0][x], $array[x][0], but I'm not sure.
I'm not really good at explaining, so I apologize in advance if anyone can't understand what I'm asking.
Try this:
// hard coding these values for example
// but for OP's case these might be coming from a previous page
$date_array = Array("01/01/2012", "01/08/2012", "01/15/2012");
$region_array = Array("NYC", "DC");
Now generate that form/table in your image like this:
<form name="test_form" id="test_form" action="submit_form.php" method="POST">
<table border="1">
<tr>
<td></td>
<?php
foreach ($date_array as $date){
echo "<td>".$date."</td>";
}
?>
</tr>
<?php
foreach ($region_array as $region){
echo "<tr>";
echo "<td>".$region."</td>";
foreach ($date_array as $date){
echo "<td><input type=\"text\" name=\"".$region."_".$date."\"></td>";
}
echo "</tr>";
}
?>
</table>
<input type="submit" name="submit">
</form>
now for submit_form.php:
if (isset($_POST['submit'])){
foreach ($_POST as $k=>$v){
if ($k != "submit"){
// split the form input on _
$input = explode("_", $k);
echo "<BR>City: " . $input[0];
echo "<BR>Date: " . $input[1];
echo "<BR>Value: " . $v;
}
}
}
This is a variant on a commonly asked question.
In principle the foreach statement is perhaps the best option. pseudocode:
Collate all possible date ranges into a single array (array_merge, array_unique, array_sort) to generate your headers
foreach($region as $dates)
{
display the button for $date['startdate'] if is in_array of dates;
display the button for $date['enddate'] if is in_array of dates;
repeat...
}
The big problem you are going to have is dealing with the layout. The obvious solution (at the risk of ire hereon) is to use an HTML table. This is simple and automatically adjusts itself.
$nextline="<TR>";
if(is in_array($datetotest,$listofdates))
{
$nextline.="<TD><CODE FOR BUTTON></TD>";
}
else
{
$nextline.="<TD><BR></TD>";
}
Your alternative (and probably slicker) solution is to enclose all your buttons in a suitable span or other tag and neatly arrange them using CSS. This gives you more layout options but can be a bit of a headache with arbitrarily large datasets.
I am doing a project in which as per number getting by GET method, I display dynamic number of HTML Textbox for storing Multiple values. I am giving each textbox unique name+id in ascending manner starting from 1(Like textbox1,textbox2). Now I want that when I click on submit button, it should fire an insert statement which insert all textbox values at once. I know I can do by array, but my question is that how to get all textbox's value in an array and How to perform insert statement?
I have done following code:
Here is PHP Code for submit button:
$schedules = array();
if(isset($_POST['submit']))
{
for($d=1; $d<=$_GET['totalDay'] ;$d++)
{
array_push($schedules,$_POST['txtSchedule'.'$d']);
}
print_r($schedules);
}
Here is the html code:
<form method="post">
<table>
<tr>
<td>Day</td>
<td>Schedule</td>
</tr>
<?php
if(isset($_GET['tour_code']) and ($_GET['totalDay']!=1))
{
$tour_code = $_GET['tour_code'];
$total = $_GET['totalDay'];
$i=0;
do
{
$i=$i+1;
?>
<tr>
<td><?php echo $i;?></td>
<td>
<input name="txtSchedule<?php echo $i;?>" type="text" size="30"/>
</td>
</tr>
<?php
$start = date('Y-m-j',strtotime($start.'+1 days'));
}while($i!=$total);
}
?>
</table>
<input type="submit" name="submit" value="Add Tour Details" />
But I am getting an empty array.
Note: $total is coming through URLString's $GET method.
Below is the output of HTML:
Simplest thing first. You have an error, you can't use
array_push($schedules,$_POST['txtSchedule'.'$d']);
You must use DOUBLE QUOTES on the $d (single quotes won't evaluate d, it will literally read "txtSchedule$d" with a dollar sign, and not actually 0, 1,..., n)
array_push($schedules,$_POST['txtSchedule'."$d"]);
//or no quotes at all
array_push($schedules,$_POST['txtSchedule'.$d]);
(that may sovlve your problems)
But now let's get to how to make an array available to the $_POST object in the processing page via form naming conventions
You're not using array syntax, but you are oh-so close. In PHP, whatever is submitted needs to be of an expected format, and iterating txtSchedule0, txtSchedule1, ...txtScheduleN is not an Array(), but $_POST[] is an array that contains each (given what you've named your input fields, which is missing 1 small thing - square brackets).
What you need to do is be naming your inputs as an array is the array name followed by square brackets (arrayName[]), here is how you create an input array of the name txtSchedule (that way when you print_r($_POST['txtSchedule']) you get an Array())
<input name="txtSchedule[<?php echo $i;?>]" type="text" size="30"/>
I had the same issue when I started in PHP, you were forgetting the square brackets around [<?php echo $i;?>]
Just make sure that if you want to do an iteration over an array of inputs:
for($i=0; $i < count($_POST['txtSchedule']); $i++){
echo "They entered " . $_POST['txtSchedule'][$i] . " in the $i" . "th position";
}
... you have used the <input name="arrayName[$i]"> sytax, or even more simply <input name="arrayName[]"> for it to auto-magically generate an array on submit in the order the inputs were in the HTML page. The naming convention is so important, and since you have it wrong (you used arrayName0, arrayName1, ... arrayNameN instead of arrayName[0], arrayName[1], ... arrayName[n]), it will never be available to you as an array.
if i understand your question correctly you are trying to retrive user input from each textbox and save it in an array?
if so I would use jquery to select all textboxes and loop through them and retrive the value
If you are looking purely at the SQL syntax, then you can just append extra records to insert at the end of your query by providing more value sets:
INSERT INTO myTable (fieldName1, fieldName2) values ("Value1A", "Value1B"), ("Value2A", "Value2B")
If you looking at the PHP logic, then my first suggestion is to use the http POST method instead of GET. Then start with processing the $_POST fields:
$data= array();
foreach($_POST as $key => $value) {
if (preg_match('/^TextBox\d+$/', $key)) {
$data[] = $mysqli->real_escape_string($value);
}
}
The construct the SQL query based on the available data
if (count($data) > 0) {
$sql = 'INSERT INTO `myTable` VALUES("' . implode('"),("', $data).'")';
// log query
// execute query
// process query results
// redirect user to a thankyou page
header('Location: thankyou.php');
}
Note that the code assumes that you have a mysqli connection instance available at $mysqli
Not sure if this is what you are looking for but should give you at least a start..
String []ar=request.getParameterValues("name");
String cmd=request.getParameter("cmd");
if(cmd==null) cmd="";
if(cmd.equals("Submit")){
for(int i=0;i<ar.length;i++) {
insert logic;
<form method="post" action="page3.jsp">
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/> <input type="submit" value="Submit" name="cmd"/>
</form>
Orignal post http://www.daniweb.com/web-development/jsp/threads/197777/insert-dynamic-textbox-value-in-database