I’m new to php and MySQL and I’m having a problem trying to work this one out.
I have this query
SELECT * FROM comments, supps
WHERE supps.tutorialid = comments.tutorialid
AND category='1'
ORDER BY $orderby $sort
LIMIT $startrow, $limit
Which is working fine, but the problem is I want to also include the AVG of a column from comments table and I can’t seem to get it to work with this query. Can anyone help me
Implicit SQL joins considered harmful
First of all please do not use implicit join syntax. It belongs in 1989 please bury it there.
It looks like you have an SQL-injection leak
if you use php and you don’t put your injected variables in single quotes
'mysql_real_escape_string()will not work!And you will be at risk of SQL-injection
Lastly you are injecting column names into your query.
mysql_real_escape_string()will not protect you when doing that, neither will use PDO or anything else. You will need to check the column names against a pre-appoved white list on order to not fall victim to SQL injection attacks. See here for more info:If you inject $vars into a limit clause
mysql_real_escape_string()does not work because MySQL does not see these as values, but as literals you need to cast them into integers to make it safe.Rewrite the query into and preceding php code to:
SQL injection protection recap
1. Always use
mysql_real_escape_string()to escape data that comes from outside. (or even better use PDO)2. Surround injected $var values in your queries with
'single quotes; if you don’t escaping withmysql_real_escape_string()will not work.3. check injected table, column and database names against a whitelist.
4. Surround $vars used for table, column and database names in backticks
`; this is not a security measure, but your query will fail if you use reserved words, numbers of (shudder) field names with spaces, backticks fix this.5. Test to see if injected $vars in your limit clause are integers.
Fail to do any of those things and your server will the pwned!.
Back to your question
My fingers hurt, but other people have kindly answered your question.
Links
SQL-injection in general: How does the SQL injection from the "Bobby Tables" XKCD comic work?
Whitelisting for injected column names: How to prevent SQL injection with dynamic tablenames?