1

I have this comment form where the only inputs are a name and a textarea for a comment.

My question is: how can I be sure that there is no way to use SQL injection in my code? I found a couple of guides for this, but I am not sure how to make them work with my code.

<?php
if(isset($_POST['submit'])){
    $pvm = date("F j, Y"); 
    $postId = $_GET["post"]; 
    $lahettaja = $_POST['name']; 
    $kommentti = $_POST['comment'];

    $sql = "INSERT INTO kommentti (post_id,kommentti_pvm,kommentti,lahettaja) VALUES (:post,:kommentti_pvm,:kommentti,:lahettaja)"; 
    $kysely = $yhteys->prepare($sql); 
    $kysely->bindParam("post", $postId); 
    $kysely->bindParam("kommentti_pvm", $pvm); 
    $kysely->bindParam("kommentti", $kommentti); 
    $kysely->bindParam("lahettaja", $lahettaja); 
    $kysely->execute(); 
}
?>
elixenide
  • 44,308
  • 16
  • 74
  • 100
Frostbch
  • 103
  • 7

1 Answers1

4

You're already secure against SQL injection. The only way to secure against it is to use prepared statements with proper parameterization. That is, use prepared statements with a parameter for every single thing that could contain user input. You're doing that, so you're in good shape.

Please note: this does not mean you can ever treat the data as "clean" or safe. You cannot, for example, pull it from the database and just echo it. Doing so opens you up to a type of attack called XSS, or Cross-Site Scripting (technically, in this case, Reflected XSS).

For more information and to learn more, see:

Community
  • 1
  • 1
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • Okay thank you very much! I really thought that i need add something to check forms or something like that. Great to know that i am doing it right. – Frostbch Jul 15 '16 at 03:46
  • @Frostbch Glad to help! – elixenide Jul 15 '16 at 03:47
  • @Ed Cottrell how about sanitizing POST data? – unixmiah Jul 15 '16 at 04:49
  • @unixmiah what about it? Proper sanitization is very difficult and very error-prone compared to proper use of prepared statements with parameterization. The latter is the gold standard for preventing SQL injection because it makes SQLi attacks literally impossible. – elixenide Jul 15 '16 at 04:52
  • @Ed Cottrell, I agree. External payload into any form is unpredictable therefore proper sanitation is very difficult. – unixmiah Jul 15 '16 at 05:03