如何使用PHP使用提交按钮从循环中获取所选数据

时间:2015-09-03 14:10:14

标签: php mysql

我使用循环查看所有当前数据userID和名称我限制了有关用户的信息。现在,每个按钮都有一个按钮,可以单击以查看有关该用户的更多信息。现在我被困在这里我不知道如何在viewDetails.php中获取所选数据以查看它。我想使用表单,我不知道在表单中放什么,所以我将有标识符来查询selectDetails.php

以下是我在selected.php中的代码

<?php
    if($result = $db->query("SELECT userID, name FROM user ")) {     
            while($row = $result->fetch_assoc())    {
                echo '<form method="POST" action="viewDetails.php"> ';

                    echo $row['userID'], '. ';
                    echo $row['name'];
                    echo '<input type="hidden" name="userid" value="'.$row['userID'].'"><br>';
                    echo '<input type="submit" name="submit" value="View More Details"><br>';
                echo '</form>';
            }
        }else{
            die($db->error);
        }
?>

继承我的代码以查看所选数据'viewDetails.php'

    <?php
if(isset($_POST['userid'])){ 
$selected = $_POST['userid'];
    if($result = $db->query("SELECT * FROM user WHERE userID=$selected ")) {     
            while($row = $result->fetch_assoc())    {

                echo $row['name'], '&nbsp;-&nbsp;&nbsp; ';
                echo $row['email'], '&nbsp;-&nbsp;&nbsp; ';
                echo $row['address'], '<br>';

            }
        }else{
            die($db->error);
        }
}
?>

2 个答案:

答案 0 :(得分:0)

添加一个包含用户ID的隐藏字段:

"SELECT * FROM user WHERE id=".$_POST['userid'].""

然后您可以通过

在PHP页面上检索ID
echo '<input type="hidden" name="userid" value="'.$row['userID'].'"><br>'
echo '<input type="hidden" name="name" value="'.$row['name'].'"><br>'
echo '<input type="hidden" name="email" value="'.$row['email'].'"><br>'
echo '<input type="hidden" name="address" value="'.$row['address'].'"><br>'

进一步思考,可以值得将所有用户数据存储在隐藏字段中(但仍然显示ID和名称)并将它们发布到PHP页面。然后它会阻止您再次查询数据库,因为您可以从第一个查询中获取所有数据(如果您将其更改为SELECT *):

appRoutes: {
  'availability/exceptions(/*string)': 'availabilityExceptions',
}

答案 1 :(得分:0)

更改查询..“SELECT * FROM user WHERE userID = $ selected”

<?php


   if($result = $db->query("SELECT userID, name FROM user ")) {     
            while($row = $result->fetch_assoc())    {
                echo '<form method="POST" action="viewDetails.php"> ';

                    echo $row['userID'], '. ';
                    echo $row['name'];
                    echo '<input type="hidden" name="userid" value="'.$row['userID'].'"><br>';
                    echo '<input type="submit" name="submit" value="View More Details"><br>';
                echo '</form>';
            }
        }else{
            die($db->error);
        }
?>
<?php
if(isset($_POST['userid'])){ 
$selected = $_POST['userid'];
    if($result = $db->query("SELECT * FROM user WHERE userID=$selected ")) {   
            while($row = $result->fetch_assoc())    {

                echo $row['name'], '&nbsp;-&nbsp;&nbsp; ';
                echo $row['email'], '&nbsp;-&nbsp;&nbsp; ';
                echo $row['address'], '<br>';

            }
        }else{
            die($db->error);
        }
}
?>