amy.damnit wrote:Since you brought this up, can you explain it more? You are saying that taking data from a form and plugging it directly in an SQL statement is dangerous??
Is that because someone could put in a nefarious SQL string within my outside SQL statement?
In a nutshell, yes, that is one implication. For example, let's say you were coding a user login system and in order to verify username/passwords, you ran this query:
$sql = "SELECT userid FROM users WHERE username='$_POST[user]' AND password='$_POST[pass]'
Now, let's say me, being the malicious hacker I am, decide to send 'admin' as the user and this as my password:
asdf' OR 'a'='a
Your query would then look like:
SELECT userid FROM users WHERE username='admin' AND password='asdf' OR 'a'='a'
Obviously, 'a'='a' is always true and thus the boolean logic for the query will be true despite the fact that 'asdf' isn't the password.
Another implication is that your SQL query strings could simply break. If you had a form for users to enter their real names, for example, and someone enters John O'Reilly, the single quote in the name would break your SQL query string (since strings are normally delimited by single quotes in the first place).
What functions such as [man]mysql_real_escape_string/man do is simply 'escape' (or prepend with a backslash) characters that would have special meanings (or adverse effects) if used in a SQL query. If you go the route of PHP5's newer MySQLi or PDO libraries and prepared statements, you simply use placeholders in the SQL query string; later, when you 'bind' variables/data to these placeholders, the DBMS's driver will automagically apply the proper escaping for you.
Note that in some instances, other security measures might be more applicable. For example, if you passed an id in the URL and wanted to use it in a query, I would suggest this approach:
$id = (isset($_GET['id']) ? (int)$_GET['id'] : NULL);
In other words, casting the id to an integer will prevent any unwanted SQL injections. Plus, since numeric data doesn't need to be quoted in SQL queries, casting it to an integer would be better than using mysql_real_escape_string() since you know that all non-numeric characters will be thrown out after it's been casted to an (int).
amy.damnit wrote:I am very concerned (and aware) of security, so if you know of any good books or website or articles, I am very open to them!!
Unfortunately I'm not aware of recent publications and whatnot - I just learn it all as I go.
EDIT: If you're just now learning SQL, one thread I might suggest you peruse would be this one. That way, if you ever come across a tutorial or example code where 'ORDER BY RAND()' is used to obtain random results, you'll simply sigh at the poor author who hasn't ever written a truly scalable piece of software.