HTML PHP form with multiple fields - php

I have a html form with 5 rows and 30 fields. Note the attached image.
I have to capture all of these fields in an array to later convert to a csv file. Each field is labelled at follows: qt1, fa1, en1, et1, ba1, qt2, fa2, etc... Instead of taking each row and adding them to an array in php one at a time is there an easy(ier) way to accomplish this?
I can easily take each row and add them to an array the issue with this i feel would be the speed of the script and the fact that i will have to write 30 lines of array data in the php script.

Is this what you are looking for?
<?php
for($i = 0; $i < 30; $i++): ?>
<input name="qt[<?php echo $i; ?>]"/>
<input name="fa[<?php echo $i; ?>]"/>
<input name="en[<?php echo $i; ?>]"/>
<input name="et[<?php echo $i; ?>]"/>
<input name="ba[<?php echo $i; ?>]"/>
<?php
endfor;
?>
On the server side, you will receive all this data in your $_POST variable anyways, so it will all be in an array regardless. This has an advantage of saving all your values of the same row with the same index and all the same data types under one array.
Not sure about performance, but code readability and maintenance is alot easier like this.

Name the input fields like input[i][j] and you can access them later in php like: $_REQUEST['input'][i][j] as a multidimensional array.

Related

Store _POST into variable to use with Page Data [duplicate]

I'm making a php script that stores 3 arrays: $images, $urls, $titles based on the input data of the form within the php file.
I want to print the values of these arrays in the first part of the page and then to pre-fill the form's input fields with the value of the arrays. Also when a user modifies an input field and clicks on "Save" the page should reload with the modfied version.
My problem is that on each call of the php file in a browser the value of the variables gets deleted. Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?
<?php
//save the arrays with the form data
$images = array($_POST["i0"],$_POST["i1"],$_POST["i2"],$_POST["i3"]);
$urls = array($_POST["u0"],$_POST["u1"],$_POST["u2"],$_POST["u3"]);
$titles = array($_POST["t0"],$_POST["t1"],$_POST["t2"],$_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Store the variables in a PHP session.
session_start();
$_SESSION['images'] = $images;
Then on next (or any other) page, you can retrieve the values as:
session_start();
$images = $_SESSION['images'];
Changing the scope of the variables to a larger scope, might do the trick. Also, check if you have a post request before updating the values.
<?php
if(sizeof($_POST) >0)
{
//UPDATE VALUES
}
?>
If you want a permanent storage of state, between different pages, you should use sessions, by putting session_start(); in the start of your script. After this, every variable $_SESSION[$x] will be persisted, and will be available to your scripts.
However, in this particular case, answering your question: "Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?", it is easier to just use the $_POST variable if it exists already:
<?php
if(!$_POST){
$_POST = array();
foreach(array("i0","i1","i2","i3") as $i) $_POST[$i]="";
foreach(array("u0","u1","u2","u3") as $i) $_POST[$i]="";
foreach(array("t0","t1","t2","t3") as $i) $_POST[$i]="";
}
foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
//save the arrays with the form data
$images = array($_POST["i0"], $_POST["i1"], $_POST["i2"], $_POST["i3"]);
$urls = array($_POST["u0"], $_POST["u1"], $_POST["u2"], $_POST["u3"]);
$titles = array($_POST["t0"], $_POST["t1"], $_POST["t2"], $_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Note: this line foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
should be enough to protect you from basic XSS attacks.
Note also that in general, it is best to follow the pattern of reloading pages with GET after POST, which makes you less susceptible to form resubmitions, in which case using sessions for storage is the better solution.
What brought me here was somewhat different kind of beast. I had problem with subsequent post request from AXIS IP camera and needed to preserve last file name across requests. In case that someone stumble here looking for some way to cache variables and SESSION is not an option maybe should look at Alternative PHP Cache:
Note: Unlike many other mechanisms in PHP, variables stored using
apc_store() will persist between requests (until the value is removed
from the cache).
http://php.net/manual/en/book.apc.php
Use sessions: http://php.net/manual/en/function.session-start.php
You can use sessions to store values and write rules to refill form fields after validations on data submit. Also function isset() is very helpful to avoid "not defined" errors.
The solution you are looking for is the session. Use $_SESSION to store value of Your variables. For example, at the end of script:
$_SESSION['images'] = $images;
and in form's input:
<input name='i".$x."' type='text' value='".(isset($_SESSION['images']) ?
$_SESSION['images'] : '')."'>

input (radio) value consists of ~2000 bytes, is there a better way?

I have a MySQL database that stores items (goods and services), and along with each item, terms (terms and conditions) will also be stored, which can be roughly 2000 bytes.
http://i.imgur.com/7t3cvSE.png
This is my basic set up
$term_options = array();
$term_options[] = "None";
$term_options[] = "massive string containing 2000 bytes or more";
...
foreach ($term_options as $term) {
?>
<label class="term">
<input type="radio" name="terms" value="<?php echo $term; ?>">
<?php echo $term; ?>
</label>
<?php
}
The above code does exactly what I want, but it feels wrong to have a massive value within a radio input (which may contain Unicode characters). Am I wrong to worry?
Before, I used a SELECT menu with option values equal to the index position of each array item:
?>
<select name="terms">
<?php
$i = 0;
for ($i = 0; $i < count($term_options); $i++) {
?>
<option><?php echo $i; ?></option>
<?php
}
?>
</select>
<?php
Then my $_POST would look something like this:
$terms = $term_options[$_POST['terms']];
It worked nicely until it came to my update form which should display the currently selected values. I wasn't sure how to compare the isset value with something generated via array.
It's simple to do this with static values, e.g.:
<option <?php if (isset($row['x']) && $row['x'] === 'x') echo 'selected'; ?>>x</option>
but while creating each option in a foreach loop, I have no idea what to do and the below doesn't work:
<option <?php if (isset($row['x']) && $row['x'] === $term_options[$i]) echo 'selected'; ?>><?php echo $i; ?></option>
$i++;
Yes, you are right in your worries. If this page is going to display many of these items and each item has a massive string like this, the final page is going to be huge. An this page will be sent by your server to the client browser. Bigger the page, bigger the time.
You are retrieving these items from a MySQL database. Each item probably has a primary key. Why don't you just use this primary key as part of the name of the radio buttons and then you may retrieve again just the selected item?
Something like
<input type="radio" name="rb_1">
where this "1" appended to "rb_" is the key of an item. Then you just need to break this string, recover the primary key and search if to recover the huge string.
This may generate another database operation, of course. But this will be nothing when compared with the transmission of a huge page with, say, 100 times 2k items.

PHP FOR loop taking values from form (post)

I have form with elements (text fields), 5 diference elements names:
name1a name1b
name2a name2b
name3a name3b
name4a name4b
name5a name5b
and php file:
for ($i = 1; $i <= 5; $i++) {
echo $i,"<br/>";
$name. $i .'a' = $_POST['name'.$i.'a'];
echo $name. $i .a;
}
It is posible read text fields with for loop or no? And pass values to sql query aswell?
you can use
extract($_POST);
like
echo $name1a;
echo $name1b;
you can access the value with the text-box names itself
It´s possible, but it´s a bad practice and I can´t recommend it you.
So, use arrays to store similar values from form (when you indexed your names, every times use arrays instead).
<input name="name[1]" ...> <!-- key isn't neccesary here, name[] will count from 0 -->
<input name="name[2]" ...>
<input name="name[3]" ...>
<?php
for ($i = 1; $i <= count($_POST['name']), $i++) {
echo $_POST['name'][$i] . '<br>'; // work directly with this variables/array, don't create duplicate vars
}
?>

how to store variable values over multiple page loads

I'm making a php script that stores 3 arrays: $images, $urls, $titles based on the input data of the form within the php file.
I want to print the values of these arrays in the first part of the page and then to pre-fill the form's input fields with the value of the arrays. Also when a user modifies an input field and clicks on "Save" the page should reload with the modfied version.
My problem is that on each call of the php file in a browser the value of the variables gets deleted. Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?
<?php
//save the arrays with the form data
$images = array($_POST["i0"],$_POST["i1"],$_POST["i2"],$_POST["i3"]);
$urls = array($_POST["u0"],$_POST["u1"],$_POST["u2"],$_POST["u3"]);
$titles = array($_POST["t0"],$_POST["t1"],$_POST["t2"],$_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Store the variables in a PHP session.
session_start();
$_SESSION['images'] = $images;
Then on next (or any other) page, you can retrieve the values as:
session_start();
$images = $_SESSION['images'];
Changing the scope of the variables to a larger scope, might do the trick. Also, check if you have a post request before updating the values.
<?php
if(sizeof($_POST) >0)
{
//UPDATE VALUES
}
?>
If you want a permanent storage of state, between different pages, you should use sessions, by putting session_start(); in the start of your script. After this, every variable $_SESSION[$x] will be persisted, and will be available to your scripts.
However, in this particular case, answering your question: "Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?", it is easier to just use the $_POST variable if it exists already:
<?php
if(!$_POST){
$_POST = array();
foreach(array("i0","i1","i2","i3") as $i) $_POST[$i]="";
foreach(array("u0","u1","u2","u3") as $i) $_POST[$i]="";
foreach(array("t0","t1","t2","t3") as $i) $_POST[$i]="";
}
foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
//save the arrays with the form data
$images = array($_POST["i0"], $_POST["i1"], $_POST["i2"], $_POST["i3"]);
$urls = array($_POST["u0"], $_POST["u1"], $_POST["u2"], $_POST["u3"]);
$titles = array($_POST["t0"], $_POST["t1"], $_POST["t2"], $_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Note: this line foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
should be enough to protect you from basic XSS attacks.
Note also that in general, it is best to follow the pattern of reloading pages with GET after POST, which makes you less susceptible to form resubmitions, in which case using sessions for storage is the better solution.
What brought me here was somewhat different kind of beast. I had problem with subsequent post request from AXIS IP camera and needed to preserve last file name across requests. In case that someone stumble here looking for some way to cache variables and SESSION is not an option maybe should look at Alternative PHP Cache:
Note: Unlike many other mechanisms in PHP, variables stored using
apc_store() will persist between requests (until the value is removed
from the cache).
http://php.net/manual/en/book.apc.php
Use sessions: http://php.net/manual/en/function.session-start.php
You can use sessions to store values and write rules to refill form fields after validations on data submit. Also function isset() is very helpful to avoid "not defined" errors.
The solution you are looking for is the session. Use $_SESSION to store value of Your variables. For example, at the end of script:
$_SESSION['images'] = $images;
and in form's input:
<input name='i".$x."' type='text' value='".(isset($_SESSION['images']) ?
$_SESSION['images'] : '')."'>

Using array of numbers to toggle radio button visibility. PHP

I have an array of numbers that can be 1-24. ($timelist) I want to use this array to make a select time form. How would I use this array to toggle the visibility of a radio button?
For example: I have array(1,2,4) and radio buttons 1AM, 2AM, 3AM, and 4AM. I want radio button 3AM to not show based on the array in my php script.
Any ideas on how to make this work?
What I got so far is a form where the user selects a date and hits enter.
It then sends them to a php file named validate.php via get method.
The script will do it's job and place available times into an array.
I want to use that array (1-24) to display the available times as radio buttons (12AM to 12PM) where the user can select one based on a time available and continue the application process.
$timelist = array( 1, 2, 4 );
foreach($timelist as $time):
echo "<input type='radio' name='time' value='$time' /> $radio AM<br />";
endforeach;
Something like that, you mean?
Edit: to have nice formatting, you could do something along the lines of
$time%12 . ( $time >= 12 ? 'PM' : 'AM' )
From your question, I understand that you initially do send the radio input to the client in the response HTML, and you want to hide it afterwards? This doesn't make much sense - simply prepare the response HTML according to the elements in the array, instead of rendering everything and than hiding it. Do something like:
<?php foreach ($timelist as $time): ?>
<input type="radio" name="time" value="<?php echo $time?>" /> <?php echo $time?>
<?php endforeach; ?>
for military time inclusion try this
<?php $i = 1; ?>
<?php while ($i <= 24): ?>
<input type="radio" name="time" value="<?php echo $i; ?>" />
<?php echo (12 < $i ? $i .' AM': ($i -12).' PM'); >
<?php $i++; ?>
<?php endwhile; ?>

Categories