PHP - get uncertain number of fields - php

I have a problem with <form> in php .
i have uncertain number of fields (inputs) . it may be 1 or 100 input field .
Is there any function or class to get uncertain number of fields ?

Try that :
echo '<form>';
foreach ($data as $value) {
echo '<input name="field[]" value="',$value,'">';
}
echo '<input type="submit"></form>';
If you send that form, $_POST['field'] will be an indexed array in which every entry will correspond to one of the inputs.

$_POST would contain all the fields from the form on submit
print_r($_POST) will display them in an array for you

You can use an array name for the input fields in your form. For example, you can make an array of title fields by adding [] after the name:
<input type="text" name="title[]" />
<input type="text" name="title[]" />
<input type="text" name="title[]" />
Now in your PHP code, this value will be an array containing an amount of values equal to the number of fields with this name. The following code would print all titles on separate lines:
foreach ($_REQUEST['title'] as $value)
echo $value . "\n";

Just count the $_POST or $_GET what you use.
<?php
if(isset($_POST['submit'])){
echo "The total number of input fields is";
echo count($_POST); // include submit also
}
?>

Related

How to post multiple entries from dynamically generated textboxes in while loop

please i am currently working on a school result computation project in php. I have a page that gets all the students that enrolled for a particular subject. A while loop generates three textboxes against each student's name(CA1, CA2, and Exam). Please can anyone help me with a solution?? When the form is submitted only the last entry enters the database. Below is my code.
<?php
session_start();
include 'header_staff.php';
$subject=$_POST['subject'];
$user_id=$_SESSION['user_id'];
$get=mysql_query("SELECT * FROM staffrecord WHERE user_id='$user_id'",$conn);
$go=mysql_fetch_array($get);
$class=$go['class_id'];
$sql=mysql_query("SELECT * FROM student_enrollment WHERE class_id='$class' AND subject_id='$subject'",$conn);
echo '<form action="submitrslt.php" method="post">';
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1" />';
echo '<input type="text" name="ca2" />';
echo '<input type="text" name="exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
?>
The solution to your problem is to use your input arrays by simply adding [] to the input names:
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[]" />';
echo '<input type="text" name="ca2[]" />';
echo '<input type="text" name="exam[]" /><br><br>';
}
Further, you can use the primary key of your table as the index in each iteration (let's suppose this would be $subj['id'], but if it is more meaningful in your case, you can also use $subj['name'] as the index):
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="ca2[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="exam[<?php echo $subj['id'] ?>]" /><br><br>';
}
This way you can easily identify values from the resulting array after the post.
PS: Be sure you never trust user input without verifying or sanitizing it - make sure $_POST['subject'] is numeric. You can find plenty of useful tips on how to achieve this.
I have added comments, this will solve your problem i am assuming your subjects data is unique for the loop. And i have defined the input with the subject name which make it unique. Just for an example you can try your own method. This will output all the post variables on your action(form post) screen.
<?php
while($subj=mysql_fetch_array($sql)){
$subname = str_replace(' ','', $subj['name']); //just to replace the space
echo $subj['name'];
echo '<input type="text" name="'.$subname.'_ca1" />'; //to make the field unique for the input entries
echo '<input type="text" name="'.$subname.'_ca2" />';
echo '<input type="text" name="'.$subname.'_exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
echo '</form>';
?>
Firstly, I would suggest changing the connection to mysqli, which follows a very similar syntax to mysql except that it is not deprecated.
Secondly, the form looks fine, except that the textboxes and submit button don't have any unique identifiers, you might try putting in a unique 'id' for each of the input fields. Since your loop is combining all input fields in one form, this is likely the culprit. Furthermore, I don't see a closing tag for form, i.e. </form>.
Finally, you should look up filter_input for handling superglobals such as $_POST[].
I assume that all fields are meant to be submitted at once rather than individually?

hidden array returns OK but text array is empty html to PHP

Form:
<form method="POST" action="edit_work.php">
<input type="hidden" name="wid[]" size="1" value="<?php echo "$wid1" ?>" >
<input type="text" name="course[]" size="15" value="<?php echo "$course1" ?>" >
PHP:
extract($_POST);
for($i=0;$i<$count;$i++) {
echo $wid[$i];
echo $course[$i];
}
gives the wid values OK but not the text entered for the course names.
I have been through all forums for 2 days now. Any help? Thanks.
If you want your PHP to retrieve your data from the form, can't you name your text input "course", then get it inside your PHP with $_POST['course'] ?
What is your $count ?
Using brackets with your name attribute inside your input tag may be dangerous.
If you're using a list of inputs maybe you can define a text format like name="course#" where # is your index and then access it form your $_POST variable using $_POST['course'.$index]
You don't need to extract($_POST) in that case.

How can I collect checked items from PHP array served in form?

I have a form which builds the form items from a foreach loop and puts a checkbox by each item:
<form action="nextStep.php">
<?php
foreach ($children[0] as $myPage) {
$menuname = $info[$myPage]['label'];
echo '<input type="checkbox" id="'.$menuname.'" name="reveal_menu" value="no" unchecked><label for="'.$menuname.'">'.$menuname.'</label><br>';
}
?>
<br>
<input type="submit" value="Submit">
</form>
As you can see, I start with each item unchecked. What I would like to know is how I should build the nextStep.php script to create individual php variables that I can echo on the nextStep.php page after the user clicks the submit button?
You must identify that this input is an array of values, by appending [] on the name:
echo '<input ... name="reveal_menu[]" ...>';
In nextStep.php:
foreach($_POST['reveal_menu'] as $checkbox)
echo $checkbox;
EDIT to answer OP comment:
You would need to create an array to handle these values. But $_POST['reveal_menu'] itself is an array. So can access $_POST['reveal_menu'][0], for example.
Keep in mind that $_POST['reveal_menu'] is an array with checked values ONLY . The index 0 doesn't point for the first checkbox of your form, but for the first checkbox checked from your form.
Each item needs to have a unique value, probably the menuname, so you can tell which ones are checked, and the name needs to have [] operator appended to the end.
<form action="nextStep.php">
<?php
foreach ($children[0] as $myPage) {
$menuname = $info[$myPage]['label'];
echo '<input type="checkbox" id="'.$menuname.'" name="reveal_menu[]" value="$menuname" unchecked><label for="'.$menuname.'">'.$menuname.'</label><br>';
}
?>
<br>
<input type="submit" value="Submit">
</form>
When you loop through, you'll get an array of values.
<?php
foreach($_POST['menuname'] as $v)
{
echo($v . 'Was checked.');
}
?>

How do I access two arrays from a form simultaneously in php?

I receive two arrays from a form. In the .php file, I need to insert the values of each array into a column of the table.
- use the foreach loop to access the elements of one array and complete the insertion for only one column. When I do the same thing for the next array, I find that the corresponding first column elements are null in each row while for the first array, the corresponding second column elements are null. Is there anyway to avoid this and insert the array elements one after the other?
- I understand that foreach cannot be applied to two arrays so is there any other way I can access both the arrays simultaneously for insertion into a table?
Thanks.
You can use a foreach loop:
foreach($_POST['someField_1'] as $key => $value)
{
$fieldOne = $value;
$fieldTwo = $_POST['someField_2'][$key];
}
Obviously change the _POST variables to whatever you've named the fields.
As long as your field names are named something like: name="someField_1[]" and name="someField_2[]" You can use the foreach loop in this way.
EDIT
Take this HTML for your input form:
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
So that form allows you to enter forenames and surnames for up to 3 people. Each field has the exact same name: forename[] and surname[]
To retrieve each of the values, you would use this PHP:
foreach($_POST['forename'] as $key => $forename)
{
echo 'Forename: ' . $forename;
echo ' ';
echo 'Surname: ' . $_POST['surname'][$key] . '<br />';
}
This works because when you submit a field like forename[], with square brackets at the end, PHP will automatically convert this to an array. $key is a number which starts at 0, and goes on for however many fields there are.
PHP uses the $key to retrieve the correct fields. You could also write your HTML like this:
Forename: <input type="text" name="forename[0]"> Surname: <input type="text" name="surname[0]">
Forename: <input type="text" name="forename[1]"> Surname: <input type="text" name="surname[1]">
Forename: <input type="text" name="forename[2]"> Surname: <input type="text" name="surname[2]">
You see I've put a number between the square brackets? PHP will detect this and loop through the arrays.
You could even use a for loop:
for($i = 0; $i<count($_POST['forename']); $i++)
{
echo 'Forename: ' . $_POST['forename'][$i];
echo 'Surname: ' . $_POST['surname'][$i];
}

how do I use value of input element in a new file (GET method)

<?php
// code that connects to database
?>
<table>
<form method="get" action="processorder.php">
<?php
while (list($pizzaId, $pizzaName, $pizzaNumber, $pizzaPrice) = mysql_fetch_row($resultaat))
{
echo "<tr>
<td>".$pizzaName."</td>
<td>".$pizzaNumber."</td>
<td>".$pizzaPrice."</td>
<td> <input type='text' name='$pizzaId' value='$qty' size='3' /></td>
</tr>";
}
mysql_close($db);
?>
<input type="submit" value="Order now" />
I would like to display the pizzas of where there is a value in the input element.
the processorder.php file would look like:
my url shows the pizzaId's with the values after the '='. So I figured I have an associative array on my hands.
I thought I'd put a foreach loop in my processorder.php going like
foreach ($_GET['pizzaId'] as $pizza => $qty)
{
echo $pizza." ".$qty."<br />";
}
Yet, when I use the foreach loop, the error in my browser says that the argument of my foreach loop is invalid because $_GET['pizzaId'] isn't an array to begin with (I checked with is_array).
So how do I get access to those values in my value attribute of the input element?
Your $pizzaId is an integer.
I would change the name of the input elements to name="pizzas[$pizzaId]", and then you could access it through PHP like this:
foreach ($_GET["pizzas"] as $pizzaId => $pizzaQty) {
echo "$pizzaId $pizzaQty<br />";
}
with this method, instead of just plain name="pizzas[]", you also retain the association with the actual pizzaId.
If you need to put an array into $_GET then your url should look like:
//site/page?pizzaID[]=123&pizzaID[]=124
You can achive this with similar usage of name of input field
<input name="pizzaID[]" />
<input name="pizzaID[]" />

Categories