Also, to expand on my comment about cleaning strings, you absolutely must do this. In the example in post #3, what happens if someone supplies the comment text hello');DROP DATABASE
Potentially, Very Bad Things Indeed. It's a classic SQL injection attempt - and never assume that your users will be innocent of malice, let alone anyone else who's simply scanning sites for backdoors, whether they want to break your site, or simply see if they can get names and passwords, or email addresses to spam.
If you're using PHP as a backend, I strongly advise using the newer MySQLi commands. It provides better protection against mysql injection, and the real_escape_string should be mandatory pretty much wherever you are putting values into a database.
Using sprintf to help construct your query can help too, as it ensures that numeric values are just that - if someone had fiddled the $_POST['ID'] parameter in the example I gave, and sent a string, since it's using %d in the sprintf, it would simply evaluate to zero, which is why I don't bother using real_escape_string - though elsewhere in my code, I usually do a check for is_numeric($_POST['ID']) as well.
If you can avoid it (which you obviously can't with things like messaging) don't put text from a user anywhere near your database; use numeric parameters.
If you have to accept text from a user, sanitise it first, with real_escape_string.
If it can only be one of a range of values, use if or select statements to make sure it really will be one of those, for example, for a checkbox you might say
if ( $_POST['opt-in'] == 'y' ) {
$optin = 'y' ;
} else {
$optin = 'n' ;
}
and then use the value of $optin in your SQL statement, instead of the value posted by the user.
You should probably also consider whether or not your script should have a separate database user, with different permissions. For example, I have a public API script that allows people to fetch calendar events from my site. That runs with a specific user that has permissions set in MySQL that allow only SELECT statements from the tables related to the calendar.
The main API script requires INSERT permissions in some tables, but not others, so it's a good idea to restrict that as well.
Most of this, of course, also applies to other server-side technologies - if in doubt, assume that what's being sent to your database server could potentially be malicious, and make sure you do everything possible to stop bad things happening.