0

I have three arrays that look like this:

ingredientQTY is the first input box in each row, measurements is the select/dropdown in each row, and ingredientsNAME is the last input box in each row. As you can see, there can be infinite numbers of ingredientQTY's, ingredientNAME's, and measurements.

picture

When I send them to my php script, the data is in arrays like:

IngredientQTY
(
  [0] => 5 //The first row 
  [1] => 5 //The next rows value
)   
Measurements
(
  [0] => Bunch  //The first row
  [1] => Bunch  //The next rows value
)   
IngredientName
(
  [0] => 5   //The first row
  [1] => 5   //The next rows value
)

I'm trying to upload them to a table called ingredients that has 3 columns: ingredientNAME, ingredientQTY, and measurements.

In my php script, I'm combining them into a multidimensional array, which is assigned to $ingredientsROW:

foreach($_POST as $key => $value) {
      $value = $this->input->post($key);
      $ingredientQTY = $this->input->post('ingredientQTY');
      $measurements = $this->input->post('measurements');
      $ingredientNAME = $this->input->post('ingredientNAME');
      $ingredientsROW[] = array($ingredientQTY, $measurements, $ingredientNAME);
      break;
}

My question is: How can I get group all the first row of form elements (which means the first ingredientQTY, the first measurements dropdown and the first ingredientNAME and insert them into a row?

The only way I could think of is to have one insert where I insert ingredientQTY, then look up the id of the row I just inserted and use two mysql updates to enter for the same row, but I'm pretty sure there is more efficient ways of going about this.

4

2 回答 2

2

Would something like this work?

foreach($_POST['IngredientQTY'] as $index=>$qty)
    mysql_query("insert into ingredients ".
                 "set IngredientQTY='".addslashes($qty)."'".
                 ", measurements ='".addslashes($_POST['measurements'][$index])."'".
                 ", ingredientNAME ='".addslashes($_POST['ingredientNAME'][$index])."');
于 2013-03-27T16:19:40.263 回答
1

Iterate through the data and create an array like this:

for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
   $rows[] = array(
       'QTY'         => $ingredientQTY[$i],
       'measurement' =>  $measurements[$i],
       'name'        => $ingredientNAME[$i]
   );
}

With this array you can create the insert quite easily and insert whole rows.

于 2013-03-27T16:12:18.163 回答