0

When I submit a form to a PHP_SELF page via POST method, The text get's inserted into the table again on every refresh. How do I fix this and prevent my textarea from being empty before insertion?

echo "<form action=<?php echo $_SERVER['PHP_SELF']; method='post'>";
echo "<textarea name='msg' placeholder='Type message here' required='required' style='width:100%;min-height:60px;min-height:60px;'></textarea>";
echo "<button>Send</button>";
echo "</form>";

And here is my PHP code to insert the text into the table 'msg'.

if(isset($_POST['msg'])&!empty($_POST['msg']))
{
    $message=$_POST['msg'];
    $message=$conn->quote($message);
    $sql="INSERT INTO msg(msg.to,msg.from,msg) VALUES('".$_SESSION["tousermessage"]."','".$_SESSION["username"]."',$message)";
    $ex=$conn->prepare($sql);
    $ex->execute();

    unset($_POST['msg']);
}
Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
user3783952
  • 107
  • 1
  • 2
  • 8

1 Answers1

0

Firstly, you're already in PHP and echo:

echo "<form action=<?php echo $_SERVER['PHP_SELF']; method='post'>";

that needs to be changed to (and would have thrown a parse error). Error reporting may not be set.

echo "<form action='' method='post'>";

Now, if you want to avoid getting entries added to your DB on a page refresh, you have a few options.

  • Use a header to redirect (to same page or a different page)
  • Use two different files, HTML form then PHP/MySQL. However, people clicking back to the previous page and doing refresh may also produce the same thing, so either way, use a header.

I.e.: (and you had a & missing in your conditional statement.

Sidenote: $message in your VALUES. That is a string and it should be quoted. I.e.: '$message'. But I left it the way it is below. Quote it if you're getting errors and you should be getting errors.

if(isset($_POST['msg']) && !empty($_POST['msg']))
    {
        $message=$_POST['msg'];
        $message=$conn->quote($message);
        $sql="INSERT INTO msg(msg.to,msg.from,msg) VALUES('".$_SESSION["tousermessage"]."','".$_SESSION["username"]."',$message)";
        $ex=$conn->prepare($sql);
        $ex->execute();

        unset($_POST['msg']);
        header("Location: http://www.example.com/yourfile.php");
        exit;
    }

However, that will only work if you're not outputting before header, such as HTML above PHP etc.

If this is the case, using ob_start(); may work, but PHP should ideally be on top of any HTML you may have.

Using sessions tokens is another option, but that may be beyond the scope of this question.

Have a look at the following page on Preventing Multiple Submits:

That works rather well, and will prevent multiple submissions.


Footnotes:

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141