Search code examples
phphtmlrow

How to insert multiple selects into separate rows


Having read several posts on this subject, I have managed to insert data from a multiple select form. However, the data goes into one row. I need each value to go into separate rows. Here is the relevant field in the form

<p>
    <label>Assign Users::</label>
    <select id="client" name="client[]"  multiple="multiple">
        <option  class="multiple" value="selected">Assign User to Project</option>
        <?php 
            foreach($clients as $client){ 
        ?>
        <option value="<?php echo $client ->user_id;?>"><?php echo $client ->user_name; ?></option>
        <?php 
        }
        ?>
    </select>
</p>

And here is the Insert code

$ref=$_POST['project_ref'] ;
$user_id=implode(',', $_POST['user']);
$wpdb->insert( 'vo_wp_assigned_projects', array('client'=>$user_id,'project'=> $ref));

This inserts into one row, which is no use as I need to be able to access each individual entry. I have tried foreach loops from other posts in this group with no success. I hope I have provided sufficient information.


Solution

  • Retrieve the array: $clients = $_POST['client']; gives you an array of selected values from the select field.

    Loop through the array: Using foreach ($clients as $client_id), you process each selected value.

    Insert separately: For each $client_id, an insert query is executed to create a new row.

    $clients = $_POST['client'];
    
    foreach ($clients as $client_id) {
        $wpdb->insert(
            'vo_wp_assigned_projects',
            array(
                'client'  => $client_id,
                'project' => $ref,
            )
        );
    }