PHP - form action calling itself, how to display everything in 1 page?

后端 未结 9 1339
暖寄归人
暖寄归人 2021-01-22 14:43

I have two .php files as such:

test1.php



    Sample


    
相关标签:
9条回答
  • 2021-01-22 15:33

    This one is fully tested and allows you to revise the value after submission. You still have to worry about cross-site scripting attacks, etc... but that is outside of the scope of the question.

    <html>
    <head>
        <title>Sample</title>
    </head>
    <body>
        <?php
        $user_number = '';
        if (isset($_POST['userNumber'])) {
            $user_number=$_POST['userNumber'];
        ?>
        <p>You have chosen <?php echo $user_number ?></p>
        <?php
        }
        ?>
        <form method="post">
        Please enter a number <input type="number" name="userNumber" value="<?php echo $user_number ?>"><br>
        <input type="submit">
        </form>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-22 15:36

    Check if $_POST["userNumber"] isset, and echo the form if it's not.

    <html>
    <head>
        <title>Sample</title>
    </head>
    <body>
        <?php
            if(isset($_POST["userNumber"]){
                echo "You have chosen ".$_POST["userNumber"];
            }else{
                echo '<form action="test1.php" method="post">';
                echo 'Please enter a number <input type="number" name="userNumber"><br>';
                echo '<input type="submit">';
                echo '</form>';
            }
        ?>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-22 15:36

    You simply need to remove the action="test2.php" section and combine both pages into one just like the following:

    <html>
    <head>
        <title>Sample</title>
    </head>
    <body>
        <form method="post">
            Please enter a number <input type="number" name="userNumber"><br>
            <input type="submit">
        </form>
    
    <?php
        if(isset($_POST['userNumber'])){
            $user_number = $_POST['userNumber'];
            echo "You have chosen $user_number";
        }
    ?>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题