0

I'm working on a project to create a blog-like webpage using PHP. I want to print the text on the screen above the form but this appears to not be possible as the variables are attempting to $_GET the data from the form before the data is entered. Is it possible to place the text above the form?

Here is my code so far: (The PHP updates the screen by putting "basic.php" (the file name) into the action attribute of the <form> tag)

<!-- 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>
imulsion
  • 8,820
  • 20
  • 54
  • 84

3 Answers3

3

It seems that you want to show the message only if it exists right?

<?php if ( ! empty($_GET['msg'])) : ?>
<i><?= $_GET['msg']; ?></i>
<?php endif; ?>
landons
  • 9,502
  • 3
  • 33
  • 46
1

Use session variable:

...
</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">
...
CAPS LOCK
  • 1,960
  • 3
  • 26
  • 41
1

Usually I solve this with a hidden variable in the form:

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

Then check for that variable before I process the form:

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

It's generally a good way to prevent the form from being processed before it's submitted - such are the perils of self-submitting forms.

CodeMoose
  • 2,964
  • 4
  • 31
  • 56
  • Keep in mind that, with strict error reporting, you'll still get a notice. Put an `isset()` check around `$_GET['processForm']` – landons Mar 08 '13 at 19:57