Khalid Khalid - 5 months ago 14
HTML Question

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

I have two .php files as such:

test1.php

<html>
<head>
<title>Sample</title>
</head>
<body>
<form action="test2.php" method="post">
Please enter a number <input type="number" name="userNumber"><br>
<input type="submit">
</form>
</body>
</html>


test2.php

<html>
<head>
<title>Sample Display Page</title>
</head>
<body>
<?php
$user_number = $_POST["userNumber"];
echo "You have chosen $user_number";
?>
</body>
</html>


I want to know how can I get it all to display on a single page, i.e. on the test1.php, without having to have two files.

Answer

Your test1.php will need to look like this

<html>
<head>
    <title>Sample</title>
</head>
<body>
    <form action="test1.php" 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>
Comments