我正在开发一个使用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>
答案 0 :(得分:3)
似乎只有在消息存在时才显示消息?
<?php if ( ! empty($_GET['msg'])) : ?>
<i><?= $_GET['msg']; ?></i>
<?php endif; ?>
答案 1 :(得分: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">
...
答案 2 :(得分: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...";
}
?>
这通常是防止表单在提交之前被处理的好方法 - 这就是自我提交表单的危险。