htmlentities() is unnecessary to make data safe for SQL. It's used when echoing data values to HTML output, to avoid XSS vulnerabilities. That's also an important security issue you need to be mindful of, but it's not related to SQL.
addslashes() is redundant with mysql_real_escape_string. You'll end up with literal backslashes in your strings in the database.
Don't use magic quotes. This feature has been deprecated for many years. Don't deploy PHP code to an environment where magic quotes is enabled. If it's enabled, turn it off. If it's a hosted environment and they won't turn off magic quotes, get a new hosting provider.
Don't use ext/mysql
. It doesn't support query parameters, transactions, or OO usage.
Update: ext/mysql
was deprecated in PHP 5.5.0 (2013-06-20), and removed in PHP 7.0.0 (2015-12-03). You really can't use it.
Use PDO, and make your queries safer by using prepared queries.
For more details about writing safe SQL, read my presentation SQL Injection Myths and Fallacies.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…