0

my code looks like this (just a example, at a few parts of my projekt there are a lot of variables more then in this example):

$pdo = new PDO('mysql:host=localhost;dbname=nameofdb;charset=utf8','dbuser','dbpass');

$surname = htmlspecialchars($_POST["surname"]);
$lastname = htmlspecialchars($_POST["lastname"]);
$street = htmlspecialchars($_POST["street"]);
$username = htmlspecialchars($_POST["username"]);

$sql = $pdo->prepare("UPDATE customer SET surname = ?,lastname = ?,street = ? WHERE username = ?");
$sql->execute(array($surname, $lastname, $street,$username));

$pdo->close();
$sql->close();

All POST variables come from forms that users can(must) fill out, so it is important that it is as safe as possible.

Sorry for this (maybe) beginner question(s), but i'm new in the PDO game, still read a lot but want to see what you people say to that code.

Please tell me what i can optimize, and above all WHY, so i can learn!

Helge
  • 11
  • 3
  • 1
    Does this answer your question? [Are PDO prepared statements sufficient to prevent SQL injection?](https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection) – ikiK Aug 28 '21 at 11:17
  • _Side note:_ Don't escape your data with `htmlspecialchars()` before yo store it in the database. Escape it when you use/output it instead. That function is for preventing XSS when outputting it on a web page, but doesn't make sense (and can cause issues) if you later on want to use the data in some API. Different use cases requires different types of escaping (or lack there of) so it's better to store it "as-is" and escape when you actually use the data. – M. Eriksson Aug 28 '21 at 11:33
  • @MagnusEriksson Thank you for this "side note": Of course you are absolutely right! Thanks for the tip :-) – Helge Aug 28 '21 at 12:05

0 Answers0