In actual programming, the HTML code of the form and the PHP program to obtain the form can be written to two files respectively, or they can be written to the same PHP file. When you first learn Web interactive programming, you can use the latter for simplicity, because doing so can reduce the number of web page files in the website.
1. Let’s look at a simple example first
<!DOCTYPE html> <html><body> <form method="POST" action=""> <!-- action内容为空或为自身文件 --> 用户名:<input type="text" name="name" size="10"> 密码:<input type="text" name="ps" size="10"> <input type="submit" name="login" value="登录"> </form> <?php if (isset($_POST['login'])) { /* 如果点击了'登录'按钮 */ $user=$_POST["name"]; $pwd=$_POST["ps"]; echo "用户名是:".$user; echo "<br />密码是:".$pwd; } ?> </body></html>
This is to write the HTML code of the form and the PHP program to obtain the form into the same PHP file.
This is the effect of clicking login after entering the username ‘BIN_GOO’ and password ‘123’.
2. Improvement method
Because after entering the user name and password, the form data and the information obtained by the server are displayed on the same page. What should I do if I want to make the form data disappear after clicking login and only the obtained information is displayed?
The method is as follows:
<?php if (isset($_POST['login'])) { $user=$_POST["name"]; $pwd=$_POST["ps"]; echo "用户名是:".$user; echo "<br />密码是:".$pwd; } else echo '<form method="post" action=""> 用户名:<input type="text" name="name" size="10"> 密码:<input type="text" name="ps" size="10"> <input type="submit" name="login" value="登录"> </form>'; ?>
This implementation can ensure that the form will no longer be displayed when outputting the information. This is because when login is not clicked at the beginning, the code in else will be executed. When login is clicked, the code in if will be executed, thus hiding the form data.
The specific output is as follows:
This is the effect of clicking login after entering the user name ‘BIN_GOO’ and password ‘123’.
The above introduces how the form code and PHP code are written in the same file, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.