-1

( Sorry for my bad english )

I am new to PHP. I have two input fields. One for the username and one for the comment. My problem is when I Reloaded my page that simply blank entries I posted my table. Why is that?

Existing Code :

$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');

if(!db){
   exit ("Verbindungsfehler:" . mysqli_connect_error());
}

$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
Jay S.
  • 1,318
  • 11
  • 29
Holyfuture
  • 3
  • 1
  • 4

1 Answers1

1

Seeing that your code is coming from a POST form, you can use a conditional statement around it.

For example, in your HTML form:

<input type="submit" name="submit" value="Submit" />

then use:

if(isset($_POST['submit'])){

$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');

    if(!db){
       exit ("Verbindungsfehler:" . mysqli_connect_error());
    }

$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);

}

another thing is to make sure that fields are not left empty, using empty() I.e.:

if(empty($_POST['username'])){
  echo "Enter a username.";
    exit;
}

also isset(). I.e.:

if(isset($_POST['username'])){
  // do something
}

You can also use a header("Location: http://www.example.com/page.php");

but make sure there is nothing else above your PHP, echo, HTML, etc.


In regards to your present code:

Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements, it's much safer.

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