1

On every refresh it posts a new message, I know this is because I'm using "$_SERVER["PHP_SELF"]", bot how do I still use it without posting a new empty message each time I visit the page?

$a = "localhost";
$b = "root";
$c = "";
$d = "database";

$connect = new mysqli($a, $b, $c, $d);

if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
}

echo "Connected successfully.<br/>";

$sql = "INSERT INTO messages (message)
VALUES ('$_POST[message]')";

if ($connect->query($sql) === TRUE) {
    echo "New record created successfully.<br/>";
} else {
    echo "Error: " . $sql . "<br/>" . $connect->error;
}

$newsql = "SELECT id, message, message_date FROM messages";
$result = $connect->query($newsql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . ", Message: " . $row["message"] . ", Posted: " . $row["message_date"] . ", IP: " . $_SERVER["REMOTE_ADDR"] . "<br/>";
    }
} else {
    echo "No messages to display.<br/>";
}

?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <input type="text" name="message">
    <input type="submit">
</form>
  • You didn't check if a value was posted. You need to add a `if( isset($_POST['message']) ) { /* $sql = 'INSERT' ... */ }` So everytime, a new record is created – Georges O. Oct 26 '16 at 00:15
  • Search for [post-redirect-get](http://stackoverflow.com/questions/10827242/understanding-post-redirect-get) – mseifert Oct 26 '16 at 00:18
  • 1
    My solution to post-redirect-get can be [found here](http://stackoverflow.com/questions/19188099/removing-post-data-so-back-button-wont-display-document-expired/19194771#19194771) – mseifert Oct 26 '16 at 00:23
  • 2
    @Akanay: for your information, it's very dangerous to do directly a `INSERT INTO ... ($_POST['something'])`. Imagine I send the value = `); DROP TABLE message;`. So I will delete all data on your table :p (and I can do worse !). Google will be your friend (htmlentities, filter_var, htmlspecialchars, ...) – Georges O. Oct 26 '16 at 00:25
  • Thank you I will look into it all, I appreciate your help very much. –  Oct 26 '16 at 00:26

0 Answers0