You need to know the data type in order to decide how to sanitize/validate input. If you have, or create, classes using Active Record or Table Data Gateway patterns, you should include logic to deal with inserts and updates, thus incorporating sanitizing and validation in your classes. This is probably the recommended way to go.
However, a very simple approach to add some sanitizing would be along the lines of
$allFieldNames = array('fieldName' => 's', 'otherFieldName' => 'i', 'yetAnotherFieldName' => 'd');
foreach ($_POST as $k => $v) {
if (!isset($allFieldNames[$k])) {
// you've missed adding this fieldname to $allTypes and need to take some kind of action
// mysql_real_escape_string() (or whatever applies to your DBMS may be an option)
// aborting the operation, i.e. not performing the sql query is another
// additionally, error_logging and/or sending yourself an email may be an idea as well
}
else {
switch ($allFieldNames[$k]) {
case 's':
$_POST[$k] = mysql_real_escape_string($v);
break;
case 'i':
$_POST[$k] = (int) $v;
break;
case 'd':
// perhaps perform some kind of date range checks.
// insert default date if invalid date is supplied? abort operation?
break;
case 'and so on for double or whatever else you have':
break;
default:
// unknown data type. abort? send email? error log?
}
}
}
As for xss, if you do not have to deal with input containing html code, you can simply wrap any data to be output in htmlentities(). Don't forget you need to explicitly specify encoding for this function if you're uing utf-8.
$result =$db->query("SELECT field, field2 FROM tbl");
foreach ($result as $r) {
echo htmlentities($r['field']) . ' ' . htmlentities($r['field2']);
}
And if you use something like TDG or AR, your classes should obviously deal with this as well.