0

I if have inputs like this one, but those 2 inputs are repeating themselves multiple times. So it could be:

    <input name="Gpodaciogolubu[]" type="text">
    <input name="Gpodaciogolubu_godina[]" type="number">

    <input name="Gpodaciogolubu[]" type="text">
    <input name="Gpodaciogolubu_godina[]" type="number">

    <input name="Gpodaciogolubu[]" type="text">
    <input name="Gpodaciogolubu_godina[]" type="number">
...

Is it possible to use while or foreach loop to get both values at the same time and insert it both in database like:

"INSERT INTO database (field1, filed2) VALUES ('$_POST["Gpodaciogolubu"]','$_POST["Gpodaciogolubu_godina"]')"

I'm coding in PHP/MySQL

Grant Birchmeier
  • 17,809
  • 11
  • 63
  • 98
FosAvance
  • 2,363
  • 9
  • 36
  • 52

1 Answers1

0

First build an array of rows to insert:

$rows = []; // or array() in PHP 5.3 and older
$l = count($_POST['Gpodaciofolubu']);
for( $i=0; $i<$l; $i++) {
    $rows[] = "("
        ."'".mysql_real_escape_string($_POST['Gpodaciofolubu'][$i])."', "
        .intval($_POST['Gpodaciofolubu_godina'][$i]) // since you have `type="number"`
    .")";
}

Then batch insert them:

mysql_query("insert into `database` (`field1`, `field2`) values ".implode(",",$rows));

This assumes, of course, that you're using the mysql extension. This assumption is based on the complete lack of any attempt to sanitize your input.

xkcd

Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592