RiotAct
RiotAct

Reputation: 773

php, handle multiple dynamic forms on same page

I know variations of this question have been asked, but this is a different question than what I have been able to find. I am building a dynamic list of subscriptions on a single page with information from the database and each subscription has a "cancel" button that uses some form data to make that cancellation happen.

Here is an example of the cancel button on each table row:

<form method="post" action="">
  <?php $token = $_SESSION['token'] = md5( session_id() . time(). rand() ); ?>
  <input type="hidden" name="token" value="<?php echo $token; ?>" />
  <input type="hidden" name="sg_subscriptionID" value="<?php echo $subscriptionID; ?>" />
  <input type="hidden" name="sg_postID" value="<?php echo $post->ID; ?>" />
  <input type="submit" class="button" name="submit" value="Cancel" />
</form>

To process the form, at the top of the file I am using <?php if(isset($_POST['submit']) {} ?>

This is not working when there are multiple forms on the page, I suspect because it can't differentiate between form data based on the input name "submit".

There isn't a definitive number of forms to be created, so I can't simply just have "submit1", "submit2". I can add a number dynamically using $count, but how would I check for an array of dynamic numbers in my form handling script?

I appreciate any suggestions for a possible better approach. I am trying to steer clear of ajax if at all possible.

Upvotes: 2

Views: 1106

Answers (2)

You can use html input arrays for multiple forms.

Example:- In you code:-

<form method="post" action="">
  <?php $token = $_SESSION['token'] = md5( session_id() . time(). rand() ); ?>
  <input type="hidden" name="token[<?php echo 'form_'.$i ?>]" value="<?php echo $token; ?>" />
  <input type="hidden" name="sg_subscriptionID[<?php echo 'form_'.$i ?>]" value="<?php echo $subscriptionID; ?>" />
  <input type="hidden" name="sg_postID[<?php echo 'form_'.$i ?>]" value="<?php echo $post->ID; ?>" />
  <input type="submit" class="button" name="submit[<?php echo 'form_'.$i ?>]" value="Cancel" />
</form>
<!-- $i is the key for loop -->

And in your php code:-

$submits = $_POST['submit'];
// $submits loks like ['form_1']
// Now take the first key
$key = array_keys($submits)[0];
// This is the token for the given submit button
$token = $_POST['token'][$key];

Upvotes: 1

david
david

Reputation: 3218

You can check for multiple forms in PHP.

for ($i = 0; $i < $count; $i++){
    if (isset($_POST['submit'.$i])){ // check for every forms
        // insert your own logic
    }
}

It doesn't matter how many forms you have, it can be identified using this code above.

Upvotes: 3

Related Questions