I have a form which looks like this:
$numOfCols = 4;
$rowCount = 0;
$bootstrapColWidth = 12 / $numOfCols;
$i=1;
for ($x=1;$x<=8;$x++) {
".$i.". Data
Firstname:*
Lastname:*
Field A:*
Field B:*
$rowCount++;
$i++;
if($rowCount % $numOfCols == 0) {
}
}
So as you can see I have a for-loop which shows 8x times the same fields. It is up to the user if he enters only one person or up to eight persons.
The form will be submitted this way:
if ($savedata=="true") {
/* create db connection */
$link = mysqli_connect("localhost", "USER", "PASSWORD", "DATABASE");
// check connection
if($link === false){
$error_db_connection=1;
}
// insert entries into database
for ($run=1;$run<=8;$run++) {
$var_firstname="firstname_".$run;
$var_lastname="lastname_".$run;
$var_field_a="field_a_".$run;
$var_field_b="field_b_".$run;
$sql = "INSERT INTO TABLENAME (firstname, lastname, praefix_title, postfix_title) VALUES ('".$$var_firstname."', '".$$var_lastname."', '".$$var_field_a."', '".$$var_field_b."')";
if(mysqli_query($link, $sql)){
$success=1;
} else{
$error=1;
}
}
// close connection
mysqli_close($link);
}
I am using again a for-loop where the total number of loops is hardcoded right now (8). What I need to achive is, that the hardcoded total number of loops is dynamic. So if a user fills out 3x the fields (firstname, lastname, field_a, field_b) than only 3 records should be inserted into my database. If a user fills out all 8 fields, than 8 records should be inserted into my database.
Right now I always get 8 entries into my database, also if a user only fills out one entry. Can you help me how am I able to achive what I need?
Every form field has his own unique name and id because of the $i that I am counting. Maybe I need to send a hidden field with the total number of filled fields? If so, how do I do that? Or any other approach?