Can only post first result of while loop

懵懂的女人 提交于 2019-12-11 22:21:36

问题


I am using a while loop to display results from a query. The while loop is working fine. In hidden fields I would like to post the values of userID and accessID to the user details page. I am submitting the form using javascript to submit from a link. My problem is that regardless of the username I click I can only post the values for the first displayed record. What am I doing wrong?

The code:

<?php
while($row = $result->fetch_array()) { ?>
    <form method="post" action="edit_user.php" id="userForm">
    <tr>
        <td>
            <a href="#" onclick="return(submitForm())"><?php echo $row['firstname'].' '.$row['surname']; ?></a> 
            <input type="hidden" name="userID" value="<?php echo $row['userID']; ?>" />
            <input type="hidden" name="accessID" value="<?php echo $row['accessID']; ?>" />
        </td>
    </tr>
    </form>
<?php } ?>

The javascript used for submitting the form:

function submitForm() {
    var form = document.getElementById("userForm");
    form.submit();
}

Thank you. EDIT - I don't want to pass the values in the url.


回答1:


you are generating multiple <form>s inside loop, move your <form> outside while loop, like:

<form method="post" action="edit_user.php" id="userForm">
<?php
while($row = $result->fetch_array()) { ?>       
    <tr>
        <td>
            <a href="#"><?php echo $row['firstname'].' '.$row['surname']; ?></a> 
            <input type="hidden" name="userID[]" value="<?php echo $row['userID']; ?>" />
            <input type="hidden" name="accessID[]" value="<?php echo $row['accessID']; ?>" />
        </td>
    </tr>        
<?php } ?>
<a href="#" onclick="return submitForm();">Submit</a>
</form>



回答2:


You're running into trouble because of this line

var form = document.getElementById("userForm");

In Javascript and HTML, an ID is supposed to be unique to a certain DOM element. In this case, you've got a whole load of form tags that have the same ID. You need to give each form a different ID, and then pass that ID to the submitForm function.

For example:

<?php
$id = 0;
while($row = $result->fetch_array()) { ?>
    $id++;
    <form method="post" action="edit_user.php" id="<?php echo "userForm".$id ?>">
    <tr>
        <td>
            <a href="#" onclick="return(submitForm("<?php echo "userForm".$id ?>"))"><?php echo $row['firstname'].' '.$row['surname']; ?></a> 
            <input type="hidden" name="userID" value="<?php echo $row['userID']; ?>" />
            <input type="hidden" name="accessID" value="<?php echo $row['accessID']; ?>" />
        </td>
    </tr>
    </form>
<?php } ?>

and then

function submitForm(id) {
    var form = document.getElementById(id);
    form.submit();
}

edit: how do I php? :D



来源:https://stackoverflow.com/questions/23902287/can-only-post-first-result-of-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!