How to save table values into array?

I have table in wordpress admin panel:

<tr>
    <td><input style="width:80%" type="text" name="ism" value="" /></td>
    <td><input style="width:80%" type="text" name="par" value="" /></td>
    <td><input style="width:80%" type="text" name="mar" value="" /></td>
    <td><input style="width:80%" type="text" name="akc" value="-" /></td>
    <td><a style="cursor:pointer;" onclick="nqsaddtr(this)">Add</a></td>
</tr>

It looks like:

Read More

enter image description here

Table can have unlimited number of rows.

I want to save all values in array and save results in database.

I have a code (it’s not working):

  $per = array();
   foreach($_POST['ism'] as $prod) {
  $ism = $_POST['ism'][$i];
  $par = $_POST['par'][$i];
  $mar = $_POST['mar'][$i];
  $akc = $_POST['akc'][$i];
  $per = array('post_id'=>$post_id,'ismatavimai'=>$ism,'parametras'=>$par,'marke'=>$mar,'akcijos'=>$akc);
  }

 /* update */
 if (!empty($prev)) $wpdb->update($wpdb->produktas,$upd,array('post_id'=>$post_id));
 else { $upd['post_id'] = $post_id; $wpdb->insert($wpdb->produktas,$per); }

It saves empty first row (without any values, just post id).

  $per = array();
  $ism = $_POST['ism'];
  $par = $_POST['par'];
  $mar = $_POST['mar'];
  $akc = $_POST['akc'];
  $per = array('post_id'=>$post_id,'ismatavimai'=>$ism,'parametras'=>$par,'marke'=>$mar,'akcijos'=>$akc);

This one is working, but of course it saves results just of first row.

How I can make everything work?

Related posts

Leave a Reply

3 comments

  1. Do:

    
    $yourArr = array();
    $i = 0;
    foreach($_POST['ism'] as $prod) {
      $ism = $_POST['ism'][$i];
      $par = $_POST['par'][$i];
      $mar = $_POST['mar'][$i];
      $akc = $_POST['akc'][$i];
    $per[$i]["post_id"] = $post_id;
          $per[$i]['ismatavimai'] =$ism;
          $per[$i]['parametras']=$par;
          $per[$i]['marke']=$mar;
          $per[$i]['akcijos']=$akc;
          $i++;
      }
    
    
    
  2. you need to generate dynamic names for your input box, like

    <tr>
        <td><input style="width:80%" type="text" name="ism1" value="" /></td>
    </tr>
    <tr>
        <td><input style="width:80%" type="text" name="ism2" value="" /></td>
    </tr>
    <tr>
        <td><input style="width:80%" type="text" name="ism3" value="" /></td>
    </tr>
    

    then you can extract it like

    $ism1 = $_POST['ism1'];
    $ism2 = $_POST['ism2'];
    

    basically you need to add your code in loop

  3. Your form elements are not generating an array for the post variable.

    Try:

    <td><input style="width:80%" type="text" name="ism[]" value="" /></td>
    <td><input style="width:80%" type="text" name="par[]" value="" /></td>
    <td><input style="width:80%" type="text" name="mar[]" value="" /></td>
    <td><input style="width:80%" type="text" name="akc[]" value="-" /></td>
    <td><a style="cursor:pointer;" onclick="nqsaddtr(this)">Add</a></td>