Submitting form with 100 <select>s to database - php

I have a pretty basic page that shows every five minutes of the day (12:00, 12:05, 12:10, etc). Next to each time is a dropdown <select> with the numbers 1-9. The name of the <select> is the name of the time it corresponds to. The user selects one of the numbers, goes to the next, selects a number, etc. until they get to the bottom and hit submit.
In the database table, each time of the day has its own row, with another field for the number.
How can I submit this form and have it insert the number based on the time of day to the proper row? I can't wrap my head around this for some reason. I don't even need to do validation. This is not a live website.

I think the name of the select should be times[] and the value should be the time.
so in php you can loop through the times[] array and get the row that corresponds to its value. Then update the count accordingly.
<select name="times[]" multiple>
<option value="19:00">1</option>
<option value="19:05">2</option>
</select>
In php psuedo code
foreach ($_GET['times'] as time) {
*sanatize
select row where time = time
update count
}

Assuming you have a table like this:
MyValues
TimeOfDay varchar(50),
Value int
And your posted form data looks like this:
?19:00=1&19:05=2
You will loop through each posted form field and use the key and value of each field to generate an update statement like this:
foreach($_POST as $key => $value)
{
update MyValues set Value = $value where TimeOfDay = $fieldName
}

it seems #dm03514 is good options, but had rather use the $_POST than $_GET, and on the process you can do like this
for($=0;$i<count($_POST['times']);$i++){
#do some action with $_POST['times'][$i]
}

Related

multiple foreach loops for different variables?

foreach ($textAr as $BachelorsDegrees)
{
foreach ($textArCert as $Certifications)
{
foreach ($textArDip as $Diplomas)
{
foreach ($textArAD as $AssociateDegrees)
{
foreach ($textArMD as $MastersDegrees)
{
foreach ($textArDD as $DoctorateDegrees)
{
foreach ($textArSD as $SpecialDegreePrograms)
{
what would be the best way to make the above code work (it's just a snippet of the entire code)? Each variable, for example $BachelorsDegrees, is a textarea box in the HTML form. I am trying to insert values from each textarea box into the database in individual rows. I got it working for one textarea box, but how to make it work for multiple textarea boxes?
Was thinking of doing an if else statement and an INSERT and UPDATE sql statement so that when one foreach loop worked, it would INSERT data into the database, then the loop would stop, then an else statement would go for the next foreach loop and an UPDATE query would update the next column for the same product instead of inserting. If I did multiple INSERT queries, I would be creating more rows for each variable, which I don't want. More rows for the values on each variable, but not rows for the actual variable. Each variable represents a column.
For example,
When the values from the BachelorsDegrees textarea get inserted into its column, the next loop will run (Certifications) into the next column. So I was thinking an UPDATE query would be effective. That way I don't have NULLS in every column.
If you have equal number of inputs for all the fields(Bachelorsdegree,certifications,etc), then you can take count of one input field into equation.e.g
$totalinputs=count($textAr);
for($i=0;$i<$totalinputs;$i++){
$bachelordegree=$textAr[$i];
$certificate=$textArCert[$i];
$diploma=$textArDip[$i];
.....
.....
//use above stored variables to insert/update into your respective table.
}

Referencing PHP array from MSSQL

Using MSSQL and PHP, I'm writing a calendar form that lists times in a user's schedule and lets him enter whether he is busy, available, etc.
Once the user submits the info, it's saved to a database.
If the user goes back to the form, he should see the form fields defaulting to the values he already entered.
Ok, so I could query the database for each day and timeslot, and use the result to determine what's shown on the form...but that's 145 calls to the database, since that's the number of timeslots the user can have in a week.
It seems there should be a way to query the database once, store the 145 results in an array, then query the array by day and time for each field.
So I've got:
$sql="SELECT * FROM committee_employee_schedules WHERE fac_id = $user_id";
$result= mssql_query($sql,$conn);
But from there I don't want to go into a while loop with mssql_fetch_array()...how would I go about querying my result set instead? Thanks.
Here's some more example code, since I seem to be failing to communicate:
<form>
<label for="7:30AM">7:30AM</label>
<select name="7:30AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
<label for="8:00AM">8:00AM</label>
<select name="8:00AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
<label for="8:30AM">8:30AM</label>
<select name="8:30AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
</form>
...and this goes up till 9:30PM, Monday-Friday, for a total of 145 dropdown fields.
Each field needs to know IF a row in the table exists for that timeslot, and, if so, select the appropriate activity.
I can grab all the records for the user using the code above, but do I then have to loop over those 145 rows for every single field on the form? Isn't there a way to stick the records into an array and reference it with results['Monday']['7:30'][Activity] or something?
So, you are getting back 145 records from the database. The results of your SELECT query will be stored in an array, and you will have to iterate through them using a loop. This loop could read the day and timeslot from the record, and store it into an appropriate array. Later, you could then reference that new array in the way you want. I'll try to put together an approximate example below.
<?php
slotData = array();//Store your results here the way you want to, see down below
$sql="SELECT * FROM committee_employee_schedules WHERE fac_id = $user_id";
$result= mssql_query($sql,$conn);
while($row = mssql_fetch_row($result)) {
$day = $row['day'];//Guessing your column name here
$time = $row['time_of_day'];//again, guessing your time here
$slotData[$day][$time] = $row;
//this all assumes "$day" looks like "monday", "tuesday", etc.
//also assumes "$time" looks like "8:00AM", "9:30PM", etc.
}
//now that data is in array the way you want, reference it later
//Assume you are currently trying to populate Monday at 8am position in calendar...
$curDay = 'monday';
$curTime = '8:00AM';
$data = $slotData[$curDay][$curTime];
//Yeay! "$data" now has all of the information for Monday at 8am.
?>
The bottom line is, iterate through your database result set and move the data into an appropriate slot of a different array, depending on where it should go. Then later, reference that different array however you like without worrying about iterating through ALL of the original records each time. Solved.

Array fill with the Id´s of a SELECT

I have to make an array with the POSTED value of one SELECT. The SELECT selects the products ONE BY ONE. First I choose one product and POST it then another product and I POST the SECOND ONE and so on.....
I want to create an array of the ID of the products that are posted by the SELECT but this array has to grow while I introduce more and more products.
I have use this but It makes the array with only the last product I have choosen.
foreach($_POST['idproducto'] as $key => $val) {
$cadenaides = $cadenaides . "$val,";
}
$cadenaides = $cadenaides . 1;
I would like the array to have all the ID of the products I choose ONE BY ONE in the SELECT.
Seems to me like you want to assign a number to each posted value. You can do this like so:
foreach(...) {
$cadenaides[] = $val;
}
Your values will the be stored in an array. You can check your array with print_r($cadenaides);.
Reading the comments above and assuming that you use MySQL I would suggest the following:
SELECT GROUP_CONCAT(id_producto SEPARATOR ',') FROM producto WHERE .... put your conditions here ..;
This will concatinate all IDs in a single string like that 1,2,3,5,8,9... in a single result, after that you can do just one POST request. Very usefull in many cases BTW.
The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. Could be very large - max: 4294967295 for 32-bit system.

Insert an option from drop list to database

I have this drop list for example:
<p>Your Age:</p>
<select>
<option value="1">0 - 13</option>
<option value="2">13+</option>
<option value="3">18+</option>
</select>
WHAT I'M DOING NOW is to take the value (1, 2, 3..) and insert it to the users table in the column age, how do I know which value belongs to age? I have a table ages with id and the age.
I'm not sure this way necessary, it's too much complicated and not effectively I think.
The other option is to take a string with the age and just put it in the column age, but this way is less dynamically and in what way I can check if the string is one from the ages?
What do you say?
Thank you.
You can either set the value of the option to match the value between the option tag when you generate the select field or you can have a look up array when you submit it - something like
$ageMap = array(
"1" => "0 - 13",
"2" => "13+",
"3" => "18+"
);
// get the value using the posted value from your select field
$ageMap[$_POST["YourAge"]];
You need to give your select a name attribute, and then you can retrieve if from the $_POST variable in PHP, e.g.
<form action="your_php_page.php" method="post">
<select name="age">
...
</select>
</form>
Then in PHP use:
$_POST['age']
you need to give select box "name" attribute by which you can take values of select box from name attribute.
<select name="ages">
<option value="1">0 - 13</option>
<option value="2">13+</option>
<option value="3">18+</option>
When you click on submit ,in code just write
$age = $_POST['ages'];
You will get value of selected age from select box.
I think you can create a attribute in the table with enum(1,2,3) and afterwards you can send value of 1, 2 or 3 to the table.
Advantages: You don´t need to save the ages in database just (1, 2, 3), You don´t need to save a extra table for ages, which is also a way (Creating a table of three ages and then relating one row in age column).
Disadvantag: Extra code (Maybe), depeding on how often you call it and how object-oriented you application is.
You can just check what ages is with a if & else and save it a global variable.

PHP Form Posting Values To Database

Basically, i have a working form where the user inputs details about their laptop to sell to my shop.
I give them a quote once they have submitted the Specs of the laptop.
At the moment i have got option boxes and checkboxes which each have a value-- for example these. ---
<label for="state">State</label><br>
<select name="state">
<option value="10">Excellent</option>
<option value="5">Good</option>
<option value="0">Poor</option>
</select><br>
The Values of the options they have selected get added up at the end and that gives them the quote - in the above example - "10" means £10 extra for a excellent condition laptop etc.
I use $_POST[state] to get the value of it to add onto the other options for the quote.
But my problem lies when i POST them to a database (so we can check when they come in).
When they get added to the database, obviously it just comes out as the values not the actually name of it like "excellent" or "good". just says "10" or "5".
Is there anyway to put the name of the option into the database instead of the value?
sure... just make sure that's what you want to do. It's usually not considered a good database practice to create denormalized tables like that, but you could do it. When you collect your post data, simply create another variable and assign a value to it based off the state value like so:
$stateText = '';
switch ($state){
case 10:
$stateText = 'Excellent';
break;
case 5:
$stateText = 'Good';
break;
case 0:
$stateText = 'Poor';
break;
default:
// bad value
$stateText = '';
}
...then store this to the database in a new column.
This is just one of many ways to do this.
You can only do it if you have a lookup, be it an array or in another table that stores the keys and values.
You should be carefuly not to store the post data directly into your database without sanitizing it, otherwise you might become subject to sql injection.
Is there anyway to put the name of the option into the database instead of the value?
There is, but it involves doing it explicitly (converting "10" into "Excellent" before inserting the value) rather than just basically tossing $_POST into the database as-is. You can make this very simple if you are building the <option>s with an array in the first place by reading the the array again and swapping the values with the keys.
$values = array(
10 => 'Excellent',
5 => 'Good',
0 => 'Poor',
);
$post_value = $_POST['state'];
$db_value = $values[$post_value];
// further validation: make sure the array key exists or use a default value
// further usage: build your HTML <options> with this array
However:
If you're going to do that, you're much better off storing the values as numbers and converting them to words when you display them (assuming the numbers do have some meaning). This also allows you to localize by providing translations.
Response to comments:
I would recommend a rating system, like 1 through 5, and calculate your price modifications internally - not directly from the user input or from a hardcoded value (in the database). This allows you to tweak the price changes from within your app, rather than from database values that were created at an earlier time, like if you decide an "Excellent" condition warrants an increase of 11 rather than 10 - unless you specifically want the prices "locked in" permanently at the time the product was posted.
Whatever you do, make sure to validate the input - I can't think of any good reason to use direct user input to calculate prices - it should be done internally based on product ids, and any other conditions. HTML source can be modified on-the-fly to post values you didn't expect from the dropdown.
You can't get it via the HTML form. But you can still do a server side that would map the values to the appropriate condition.
You can use a switch statement or an if statement to map them.
if(value == 10){
$condition = 'Excellent';
} else {//....}

Categories