0

I wanted to split my variables from a form, and enter them into a Mysql Database one by one. My table 4 fields would be: UserID, Status, HowLate, PassFail In this example below the UserID would be 75 and 76, but can be any # from the user id in the future. I am confused on how I would be able to insert these dynamic variables into the database since I don't know what they will be each time. The only static pattern I have is when I loop through foreach ( $_POST as $key => $value ) any help

$results = print_r($_POST, true);

sample data from form

75=PRESENT

d75=on time

cc75=passed


76=LATE

d76=10 minutes

cc76=failed

I would want to write a query like:

insert into attendance (UserID, Status, HowLate, PassFail) values (76, 'Late', '10 minutes', 'failed')

also think of this as students in a class, so there is 20 records coming back at once

Heather McVay
  • 939
  • 3
  • 15
  • 31

2 Answers2

2

I'm guessing the reason you're doing this is because you're unaware that you can send multidimensional arrays in HTML forms. I suggest an approach such as.

<input name="users[1][userid]" />
<input name="users[1][status]" />
<input name="users[1][howlate]" />
<input name="users[1][passfail]" />

<input name="users[2][userid]" />
<input name="users[2][status]" />
<input name="users[2][howlate]" />
<input name="users[2][passfail]" />

Then in php you can access them in the following manner.

foreach( $_POST['users'] as $key => $user )
{
    $userID = $user['userid'];  // same for the other fields. 
}
aziz punjani
  • 25,586
  • 9
  • 47
  • 56
  • Also, perhaps some searching might help you: http://stackoverflow.com/questions/2433727/submitting-a-multidimensional-array-via-post-with-php – art2 Jan 07 '13 at 19:54
0

Assign your variables (if you are not using PDO, which you should to avoid SQL injection) for example:

$userId = $_POST['userId']; // assuming that is what your field id is from the html form
$status = $_POST['status'];

etc.

Then insert into the database table:

insert into attendance (UserID, Status, HowLate, PassFail) values ($userId, '$status' etc.
Jim
  • 1,315
  • 4
  • 17
  • 45