João Neves
João Neves

Reputation: 77

Getting last value from multidimensional array outside foreach loop

So I'm updating a database table and I receive a array from the input because there are multiple values (id[] , price[] , product[] , description[] and so on) but I want to get the LAST value of price[] outside foreach loop I use this foreach loop that works to update the MAIN db table

foreach ($_POST['id'] as $key => $id) {
    $array1 = $_POST['product'][$key];
    $array2 = $_POST['priceunit'][$key];
    $array3 = $_POST['quantity'][$key];
    $array4 = $_POST['sum'][$key];
    $array5 = $_POST['totalprice'][$key];
    $query = $link -> prepare("UPDATE table SET product = ?, priceunit = ?, quantity = ?, sum = ?, totalprice = ? WHERE id = ?");
    $query -> bind_param('sddddi',$array1,$array2,$array3,$array4,$array5,$id);
    $result = $query-> execute();
    $query -> close();
}

and now I want to get the LAST VALUE from $array5 so I can do this outside the loop

$sql = $link -> prepare("UPDATE table2 SET price = ? WHERE id = ?;");
$sql -> bind_param("ds",

    $total,  <- array5 last value
    $_GET['id']);

$query = $sql -> execute();
$sql -> close();

this is the input

<tbody>
<?php
        $sql = $link -> prepare("SELECT * FROM table WHERE id_proposta = ?;");
        $sql -> bind_param('s',
             $_GET['id']);
        $sql -> execute();
        $result = $sql -> get_result();
        for ($i = 0; $r = $result -> fetch_assoc(); $i++){ ?>
        <tr>                                
            <input type="hidden" value="<?php echo $r['id']; ?>" name="id[]">                               
            <td><textarea class="form-control" name="product[]" rows="3" id="textareaAutosize" data-plugin-textarea-autosize><?php echo $r['product']; ?></textarea></td>       
            <td><input type="text" class="priceunit" value="<?php echo $r['priceunit']; ?>" name="priceunit[]"></td>                                                                
            <td><input type="text" class="qtd" value="<?php echo $r['quantity']; ?>" name="quantity[]"></td>
            <td><input type="text" class="sum" value="<?php echo $r['sum']; ?>" name="sum[]" readonly></td>
            <td><input type="text" class="totalprice" value="<?php echo $r['totalprice']; ?>" name="totalprice[]" readonly></td>                                                            
        </tr>
<?php } $sql -> close(); ?>
</tbody>

Thanks.

Upvotes: 0

Views: 99

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79014

Since you do this in the loop:

$array5 = $_POST['totalprice'][$key];

Then after the loop is finished, $array5 will be the last $_POST['totalprice']. So just use it:

$sql->bind_param("ds",    
    $array5,
    $_GET['id']);

Or even this if you don't use all those temporary variables:

$sql->bind_param("ds",    
    $_POST['totalprice'][$key],
    $_GET['id']);

Upvotes: 2

Related Questions