0

我正在开发一个使用 PHP 创建类似博客的网页的项目。我想在表单上方的屏幕上打印文本,但这似乎是不可能的,因为变量在$_GET输入数据之前试图从表单中获取数据。是否可以将文本放在表单上方?

到目前为止,这是我的代码:(PHP通过将“basic.php”(文件名)放入标签的action属性来更新屏幕)<form>

<!-- this file is called basic.php-->
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
<style type = "text/css">
h2
{
color:#FF2312;
text-align:center;
font-family:Impact;
font-size:39px;
}
p
{
font-family:Verdana;
text-align:center;
color:#000000;
font-size:25px;
}
</style>
</head>
<body>
<?php 
    $subject=$_GET["msg"];//variable defined but attempts to get unentered data
?>

<i>  <?php print $subject;//prints var but gets error message because $subject can't get form data ?></i>
<!--want to print text above form-->
<form name = "post" action = "basic.php" method = "get">
<input type = "text" name = "msg">
<input type = "submit">
</form>

</body>
</html>
4

3 回答 3

3

似乎您只想在消息存在时才显示消息,对吗?

<?php if ( ! empty($_GET['msg'])) : ?>
<i><?= $_GET['msg']; ?></i>
<?php endif; ?>
于 2013-03-08T19:44:25.520 回答
1

使用会话变量:

...
</head>
<body>
<?php
    session_start(); //if is not started already
    if(isset($_GET["msg"]))
        $_SESSION['subject']=$_GET["msg"];
?>

<i>  <?php if(isset($_SESSION['subject']))
            print $_SESSION['subject']; ?></i>
<!--want to print text above form-->
<form name = "post" action = "basic.php" method = "get">
...
于 2013-03-08T19:39:35.033 回答
1

通常我用以下形式的隐藏变量来解决这个问题:

<form name = "post" action = "basic.php" method = "get">
<input type = "text" name = "msg">
<input type = "hidden" name="processForm" value="1">
<input type = "submit">
</form>

然后在处理表单之前检查该变量:

<?php 
    if($_GET["processForm"]){
        $subject = $_GET["msg"];//variable defined but attempts to get unentered data
    }else{
        $subject = "Form not submitted...";
    }
?>

这通常是防止表单在提交之前被处理的好方法——这就是自提交表单的危险。

于 2013-03-08T19:45:02.820 回答