简体   繁体   中英

How can I get value of a text box which is looped using post method to insert value in database?

I had following code.My textbox attend is looped for number of times.I want to get value of each attend when my form is post to insert value in database.

 <form method="post" action="insert.php">
<label>Subject</label>
<input type="text" maxlength="30" name="subject" />
<label>Total Lectures</label>
<input type="text" maxlength="30" name="total" />
<table width="537" border="1">
 <tr>
   <td width="90">Name</td>
   <td width="139">Roll Number </td>
   <td width="136">&nbsp;</td>
   <td width="144">Attendence</td>
 </tr>
     <?php 
 $query=mysql_query("SELECT * FROM STUDENT");
 $i=0;
 while($rec=mysql_fetch_array($query)){
 $i++;

  ?>
   <tr>
   <td><?php echo $rec['name']; ?></td>
   <td><?php echo $rec['roll_number']; ?></td>
   <td>&nbsp;</td>
   <td><input type="text" maxlength="10" name="atten" /></td>
 </tr>
 <?php } ?>
</table>
 <input type="submit" value="submit" />
</form>

and my insert.php page is

if($_SERVER['REQUEST_METHOD']=='POST'){
$query=mysql_query("SELECT * FROM STUDENT");
while($rec=mysql_fetch_array($query)){
$attend=$_POST['atten'];
$subject=$_POST['subject'];
$total=$_POST['total'];

$query1=mysql_query("INSERT INTO course   VALUES('$i','$subject','$total','$attend','')") or die(mysql_error());
}
}

I am getting only 1 value of text box.

The problem is that you have many inputs all with the name atten . When you post this form, only one of those values will be carried forward.

If you change the name to atten[] all of the values would be posted as an array, which you would then have to loop through to build you insert query.

You could access this posted array as follows:

$attendee_array = $_POST['atten'];

foreach($attendee_array as $attendee) {
    // perform insert or build insert query (prefereable as you can do all these inserts at once) here
    // make sure to escape your data for input
}

Change the names of your inputs:

<input name="subject[]" value="Lorem" />
<input name="total[]" value="ipsum"  />
<input name="atten[]" value="dolor" />
Then:

$_POST['subject'][0] == 'Lorem'
$_POST['total'][4] == 'amet'

If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "subject". etc.

You need to use input array like:

<input type="text" maxlength="10" name="attend[]" />

And then you will get all the values of attend in an array and you can loop through that $_POST['attend'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM