简体   繁体   中英

How to get a specific (POST) value from foreach loop instead of getting the last index in PHP?

I am trying to echo the index or the $key when I click the button Update Payment. Bellow is a foreach loop that prints 8 cards from the database with a button on each box and hidden input value.

<?php
foreach ($cards as $key=> $row):
    $items[] = $row;
    echo "<br>";
    ?>
    <div class="card">
      <div class="card-body">
        <h5 class="card-title"><?echo $row['Holder_Name'];?></h5>
        <input type=hidden name=key_val value=<?= $key  ?>>
        <p class="card-text">Visa ending in <?echo $row['Card_ends']?></p>
        <?
        if ($row['is_active']!=1){
        echo'<button name="update_card" class="btn btn-warning ">Update Payment</button>';
        ?> 
        
      </div>
    </div>
<?
endforeach;

if(isset($_POST['update_card']) && isset($_POST['key_val'])) {
    $keyBuy = $_POST['key_val'];
    //$card_Name_DB=$items[$keyBuy]['Holder_Name'];

    echo "$keyBuy"; //issue here, it prints last index instead of the button selected
}

Expected: Echo the $key of the current button instead of the last index.

Current output: 8 //which is the same output for all buttons

I think your code create the 8 hidden fields with the same name(key_val).And all the fields are wrap in the same form. therefore your output return the last key value.

You could change the name of the key_val with key_val[] . Then, you can get the all key_val ues in an array

<form>
<input type="hidden" name="key_val[]" value="1" />
<input type="hidden" name="key_val[]" value="2" />
</form>   

Result:

Array
(
    [key_val] => Array
        (
            [0] => 1
            [1] => 2
        )
)

Solutions:

There are two method you can follow:

1> Wrap the cards on the different forms. So, you can get the data for each from separately.

2> You can use the jquery and ajax to achieve.your goal. you can, set the attributes key_val on the submit button and get with help of jquery and send to php file by ajax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM