This is actually quite a hard topic. BillyK may have a semi-viable approach but it's better to let MySQL do the hard work for you; therefore:
-
- Run the user-constructed (ie unsafe) query in a MySQL Transaction.
-
- How many results does it give? (Check for both rows returned and rows affected)
-
- Record any MySQL error warning logs.
-
- Cancel / rollback the Transaction. So that nothing has changed on your database.
-
- Re-run the query with the paramaterised variable (ie safe)
-
- How many results does it give? (Check for both rows returned and rows affected)
-
- Check if (6) gives a different number of results to (2) or if (5) gives any SQL error warnings. You can also use PHP array comparison features to check if the result sets are equal.
-
- Any positives come up, such as differences in result counts, result set eqauality or SQL warnings, then record that query string into a save file for human review.
Concept Thoughts:
With a properly implemented system of Prepared Statements it is not possible for SQL injection to occur from user variables as data strings. Therefore, rather like people throwing water balloons at tanks; it's also pretty worthless to try and "detect" these infractions; they in themselves don't show you anything more than someone read some website that offers such methods.
Therefore, as long as you have built your PHP/SQL correctly then any number or any quality of SQL injecton attempts are just water off a ducks back, and you cumulatively waste more processing power and time and effort trying to detect and record them than you would simply to ignore them.