What sanitisation should be done to form inputs before inserting into a MySQL database?
I have just 2 user-entered inputs in my PHP web application which will be sent to a series of successive pages (both via GET and via POST), before they are eventually stored into a MySQL database.
Both are text inputs (e.g., <input type="text />"
). The first is a field which should be filled by a Google maps api javascript, but which I nevertheless obviously can't trust; the second is a freely entered username
field, which at the moment only has a restriction on the string length.
What server-side checks or transformations should I perform on the values of these two fields before inserting them into the database, to prevent malicious actions, or other errors perhaps with special characters?
I am using PDO prepared statements for all my database operations, like:
$id = '1234567';
$username = 'John Smith'; //Could be weird characters like "Seán Óg Ó hAilpín"!
$Query = $db->prepare("INSERT INTO `MyTable` (`id`, `username`) VALUES (?,?)");
$Query->execute(array($id, $username));
If the values should be encoded or transformed, how should they be unencoded before displaying in HTML?
(All my other form variables are the result of choices from drop-down select
menus, and I thought of validating & sanitising their values by simply exiting the receiving script if any of them was not (!===
) any of the limited number of variables I am expecting. I'm hoping this 'whitelisting' method would be sufficient for those.)