简体   繁体   中英

$_POST[] - to different submit buttons that are not constant

I got stuck on some tricky situation. Well, here's the important part of the code:

> if (mysqli_num_rows($result) > 0) {
  // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $name = $row["name"];
        $votes = $row["votes"];

        echo " name: '" .$name. "' - votes: '" .$votes. "' <input type='submit' name='".$name."' value='".$name."' ><br>";
    }
    if (isset($_POST[''])) {

    } 
    else {
        echo "0 results";
    }
 }

What I'm trying to do is printing the table row's with a submit button near each row, which works perfectly fine. Now, I want the submit button to send data for the db once pressed.. The problem is there's more then one button, and each button gets a different name (by the data from the database table) (as shown in the code). So how exactly do I call each button specifically from the POST[] , because as you can see the if statement is out of the while loop. Help please!

Thanks a lot!

may be you can try to create a form for each row like this

<?
if (mysqli_num_rows($result) > 0) {
  // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $name = $row["name"];
        $votes = $row["votes"];
        echo '<form method="POST" action="script.php">';
        echo " name: '" .$name. "' - votes: '" .$votes. "' <input type='submit' name='".$name."' value='".$name."' ><br>";
        echo '<input type="hidden" name="submitted_vote" value="'.$row['id'].'" />';
        echo "</form>"

    }
 }
if (isset($_POST['submitted_vote'])) {
    echo 'The submmitted vote is : '.$_POST['submitted_vote'];
} 
else {
    echo "0 results";
}

Your main issue is that you're using different a different name attribute for each submit button. You want to use the same name for each submit button with a different value, and your form will only submit the value for the clicked button.

For example:

<form action="46792098.php" method="post">
<div>
<button type="submit" name="submit_id" value="1">1</button>
<button type="submit" name="submit_id" value="2">2</button>
<button type="submit" name="submit_id" value="3">3</button>
<button type="submit" name="submit_id" value="4">4</button>
<button type="submit" name="submit_id" value="5">5</button>
</div>
</form>

If the PHP code is:

<?php
var_dump($_POST);

And you click the #5 button, your output would be:

array (size=1)
  'submit_id' => string '5' (length=1)

Then your logic would just check the submit_id form parameter to determine which button was clicked.

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