dongtaogou6226 2012-06-28 09:49
浏览 48
已采纳

$ 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.

  • 写回答

9条回答 默认 最新

  • dongxun5349 2012-06-28 09:51
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类