Can someone explain this sample PHP code for me?

Tags: php html

I am doing my independent study on PHP and HTML in w3school and I don't understand the following codes: (copied from the w3school)

1  <!DOCTYPE html>
2  <html>
3  <body>
5  <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
6    Name: <input type="text" name="fname">
7    <input type="submit">
8  </form>
10 <?php
11 if ($_SERVER["REQUEST_METHOD"] == "POST") {
12     // collect value of input field
13     $name = $_POST['fname']; 
14     if (empty($name)) {
15         echo "Name is empty";
16     } else {
17         echo $name;
18     }
19 }
20 ?>
22 </body>
23 </html>

Q1: Why can I, and how should I insert a PHP code in the middle of a bunch of HTML codes like what the sample did in line 5? What topic should I look at to learn more about this kind of operation?

Q2: In the PHP codes after line 10, why would I want to include a if statement to decide if the request method is "POST"? Can't I just go to the other if condition, as in the one to check it the text box is empty?

Appreciate your help(:


Answer of question 1:

  • You can add your php code anywhere in the HTML document. You have to use

This video can help you solving your question :)
By: admin