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.
Related
The newbie is back with another question. Any help would be much appreciated. Suppose we have got a form in which we have written down the name of a user and in front of which there is an input box in which we can allocate a grade to the mentioned user. Within this scenario, everything is clear. We have a form with the name of user (it's 'id' as the value) and another variable, that is the grade' which are posted to the php-action-page. Hence, in the php-action-page, I get two variables, one is the id of the user and the other allocated grade, through POST. Here, everything is clear and the process easy, since I have got just two defined variables. Now, suppose that we are inserting a list of users from our 'Users' table into the form dynamically. We fill our form with for example 10 users grabbed from the database. In front of them there are input boxes for the 'grade' to be inserted into. So far, everything is fine. The problem, though, lies in the next stage. The problem is I don't know how to ask php-action-page to do the insert, that is insert the grade in the database for specific users as long as there are posted variables of users. Here I have tens of users and tens of dynamic variables. And if the question is a little bit vague, please do excuse me; yet, do your best to get me free from this condition of bafflement. Many thanks.
Here comes some bits of the code to make the problem a little more clear.
I start with the following code:
<?php
require_once ('../inc/takein.php');
$pd = new dbase();
$students = $pd->run_a_query('SELECT * from `checking`');
Here I am including the database and other necessary files. Then I run a query to fetch a list of my students from the table. So far, everything is fine. The next line of action which makes me perplexed is the following code.
Before having a look at the code may you please look at the html design in the following picture:
Final Design
I totally have no idea about it being wrong or correct. You might help with this bit as well.
<form action="grades.php" method="post">
<table class="table table-bordered font-label" id="item_table">
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade[]" class="form-control omit-radius-input"></td>';
echo '<input type="hidden" name="id[]" value="'.$student['id'].'">';
echo '<tr>';
}
?>
</table>
<input type="submit" name="dispatched" class="btn btn-green">
</form>
Here, I am putting the information in a table within the form element. As you can see in the above picture, I am getting four students from the database. Now I want to send these students back to the database along with their newly set grades. What I want to be posted here is the student id and their grades.
Then, the following is the last part of the code which is left incomplete because I couldn't make any senses how to do it.
if (isset($_POST['dispatched'])) {
$id[] = $_POST['id'];
$grade[] = $_POST['grade'];
// what to do now???!!!
foreach(...HOW TO DO THE 'FOREACH') {
...
}
}
May you please help me insert my student grades. Many thanks in advance.
Simply name your variables as arrays - if your form looks like this
<form method="POST">
<input type="text" name="grade[12]">
<br>
<input type="text" name="grade[15]">
<br>
<input type="text" name="grade[7]">
<br>
<input type="text" name="grade[21]">
<!-- continue here -->
</form>
then in your PHP code you will access the grades like this
if(is_array($_POST['grade'])) foreach($_POST['grade'] as $id => $value)
{
// REPLACE INTO user_grades(user_id, grade) VALUES($id, $value)
}
UPDATE
You should also put the ID of your students in the name of the INPUT field - otherwise you won't know for which student is the given grade.
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade['.$student['id'].']" class="form-control omit-radius-input" value="'.$student['current_grade'].'"></td>';
echo '<tr>';
}
?>
The foreach is shown above in my original answer.
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 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.
I have a table of questions, and I'd like to use a foreach loop to print out each question separately with a text box and a checkbox next to it. I then need to be able to take any question that is checked and do stuff to them--specifically, take the id of the question and place that in a junction table, as these questions are to be added to a printable file. (It's a test question database). I know how to do foreach loops, but I was wondering if this was possible, and how to iterate the values to make sure each textbox corresponds to a checkbox and the right values are obtainable.
I hope that makes sense.
You should just be able to do something like this:
(except that this is not a For Each loop, same concept applies)
<? for ($xlist=0; $xlist<9; $xlist++) { ?>
<input type="checkbox" name="checkSel" id="check_<? =xlist ?>"> <input type="text" value="<? =$yourValue ?>" name="quest" id="quest_<? =xlist ?>">
<? } ?>
That will paint out a checkbox and a question with the same identifier. That way you can make sure they relate to each other.
Create an incrementing integer for your loop and put this inside:
echo "<input type='checkbox' name='" . $loopIncrementVariable . "' value='" . $valueFromDatabase"'>";
You can do the same for the textbox, assigning it the same incrementing value from the loop. They will then both have the same id which can be used to match each other.
Thank you so much for being so helpful. Owe you all a thank you. I will be asking more questions in the future. Someone has solved the problem by giving me this code:
echo "" . strval($row['style']) . "" . "";
and it worked beautifully!!!!!!!!! You rock!
I am sorry, I don't know how to post follow up questions, so I keep posting each question as a new question. I've never joined any forum before, so don't know how to follow a thread :( Sorry
I previously asked a question, but didn't post my code, so many kind people (thank you so much) who respanded couldn't help me out.
So I'll post my partial code below.
";
echo "Select an item";
echo "";
}
while($row = mysql_fetch_array($result))
{
echo "$row[style] $row[color]";
}
mysql_close($con);
echo "";
echo "";
echo "Enter your 4 digit postcode";
echo "";
echo "";
echo "Enter quantity";
echo "";
echo "";
echo "";
echo "";
?>
Then to process form, I use $_POST['item'] to find out which item was selected, I get the first word, the rest of the words are missing.
For example, if the dropdown box was populated with the follwoing:
Dressmaker mannequin size 12
Mannequin torso PH-9 in skin color
...
if item selected was "Dressmaker manenquin size 12", $_POST['item'] gives me Dressmaker, the rests are missing.
I spent whole last night and today searching, but have made no progress, please help :(
This still applies from my previous post:
//====== Begin previous post
Hopefully, your MYSQL database has a primary key? If it does, set the value of each <option> to the primary key of the item.
For example:
SQL
id desc
1 "dressmaker thing with mannequin"
2 "dressmaker thing no mannequin"
Form PHP
echo "<option value='".$query['id']."'>".$query['desc']."</option>";
When the form is submitted, re-query the database for the desired description. You'll be doing this re-query anyway to retrieve prices and such, yes?
The reason this is happening is that spaces are discouraged in HTML attributes. You shouldn't have an attribute like value='this attribute is spaced'.
//====== End previous post
Basically, change this line:
while($row = mysql_fetch_array($result))
{
echo "<option value=$row[style]>$row[style] $row[color]</option><br />";
}
to
while($row = mysql_fetch_array($result))
{
echo "<option value='".$row['id']."'>$row['style'] $row['color']</option><br />";
}
and add this in process_form.php to get the description:
$desc = mysql_query("SELECT style FROM products WHERE id='".$_POST['item']."';");
You can also use this to get all other related info from the DB right when you need it.
// Another edit
#Cambraca - right on - I forgot to sanitize the quote.
#Ottoman - Your solution is a temporary fix. I strongly recommend applying an id/primary key system if it's not in place. An ounce of prevention is worth a pound of cure.
That is because in php you get what is in the "value" attribute of the dropdown's options.
You need to do something like this:
Replace
echo "<option value=$row[style]>$row[style] $row[color]</option><br />";
with
echo "<option value=\"$row[style] $row[color]\">$row[style] $row[color]</option><br />";
The problem is your lack of quotes in the option "echo" statement.
Try something like this
while($row = mysql_fetch_array($result))
{
printf('<option value="%s">%s %s</option>',
htmlspecialchars($row['style']),
htmlspecialchars($row['style']),
htmlspecialchars($row['color']));
}
Note also, the <br> element does not belong in the <select>
Edit: Added htmlspecialchars to properly escape any HTML entities that might exist in retrieved strings
If it gives you only the first word, then you forgot to enclose the option value="with quotes". Otherwise show us the constructed HTML source.