Frostbch Frostbch - 1 year ago 38
SQL Question

How to disable SQL injection possibility in a simple form?

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.

$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);

Answer Source

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: