$ PHP_SELF在页面加载后立即执行

I've created a HTML page to enter data to a MySQL database. I've embedded PHP code within the same HTML page. Here is the code,

<html>
<head>
</head>
<body>

<?php

/* Database connection operations */
require_once("db_handler.php");

$conn = iniCon();
$db = selectDB($conn);

?>

<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
    <form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
        <table width="300" border="0">
          <tr>
            <td>Location ID</td>
            <td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
          </tr>
          <tr>
            <td>Code</td>
            <td><input type="text" name="code" style="text-align:right" /></td>
          </tr>
          <tr>
            <td>Location</td>
            <td><input type="text" name="loc" style="text-align:right" /></td>
          </tr>
        </table>
</div>
<br/>
<div id="buttons">
    <input type="reset" value="Clear" /> <input type="submit" value="Save" />
</div>
    </form>

<?php

/* Saving new record */
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];

$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";

if (!mysql_query($query, $conn))
{
    die("Error " . mysql_error());
}
else
{
    echo "<br/><br/>";
    echo "1 record added successfully!";
    echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}

mysql_close($conn);

?>

</body>
</html>

The problem I have is, the PHP code block which is written to insert the data to the database gets executed once as soon as the page loads. How can I stop this from happening? I want it to wait until I enter the data to the form and when I press the submit button, then gets executed.

Thank you.

First give a name to the post button like

<input type="submit" value="Save" name="GoBtn" />

Put the code to execute after submit inside the below wrapper

if(isset($_POST['GoBtn'])
{
  //code here
}

You need to check whether any data was submitted and only then go to work:

if (!empty($_POST)) {
    ...
}

Your code for saving data should be in if (!empty($_POST)) block.

You just need to check is submit or not.

<?php
if(isset($_POST['submit']))  // Check if form submitted or not
{
  --- //Code for insert to database.
}
?>

place the php code inside an IF

if(isset($_POST["submit"])){ // if form is submitted
 // do insert things
}

You php page is interpreted as a flow : it means first displaying the form, then executing the php code part, inserting null values (i guess).

in the script part you have to test if you are in a form display context or form submit context using something like :

if ($_POST) {
   // form submit context
}

Change the submit button tag as:

<input type="submit" name="submitForm" value="Save" />

And prior executing the PHP code which inserts, check for submitForm as:

if(isset($_POST["submitForm"]){
//follow the insertion PHP code
}
  1. You must check if there are variables available in $_POST before inserting into database.

    if(!empty($_POST["lid"])) {
    /* Saving new record */ $id = mysqli_real_escape_string($_POST["lid"]); $code = mysqli_real_escape_string($_POST["code"]); $location = mysqli_real_escape_string($_POST["loc"]);

    $query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";

    if (!mysql_query($query, $conn)) { die("Error " . mysql_error()); } else { echo "

    "; echo "1 record added successfully!"; echo ""; }

    mysql_close($conn); }

  2. Use mysqli_* functions, mysql_* functions are depreciated now.

  3. use mysqli_real_escape_string() before inserting into database to prevent sql injection.
  4. You should move this database insertion area to the top of the page and use "header('location: locations.php');" for redirection.

Execute the PHP code block depending on the existance of the posted data. For refining you can even test the posted values semantically.

if ( (array_key_exists('lid', $_POST) 
AND  (array_key_exists('code', $_POST) 
AND  (array_key_exists('loc', $_POST) ) {
   then execute PHP code block
}