允许用户在防止SQL注入的同时执行mySQL选择语句

I was planning on making an HTML form. The form will display the current table in the database as shown below

Toy  | Color
Ball |  Red
Bat  |  Yellow
Glove|  Brown

At the end of the form, it should say "Make a query that gets all the toys and its respective color". So then users would be allowed to type in the select query. Please note the questions could vary so there isn't a consistent query that the user will always have to use. In essence, they have to write the ENTIRE query. I was wondering how should I go about this to prevent SQL injections.

As I stated in the comment, you can not safely do this on a live environment.

However...

If this is for educational purposes I would suggest you create a local environment on your students systems (XAMPP or the likes) and let them tinker in scripts you have premade for them.

You could set the permissions on your MySQL user to ensure they are permitted to run SELECT statements only, and only against a single database. This will allow students to experiment with maximum flexibility, and not be hindered by an overly restrictive filtering strategy.

If you run this using PDO in an exception handler, you should be able to catch any malformed queries, whether deliberate or not. If the user attempts to run a statement that is not a SELECT, that will result in a PDO Exception which can also be caught and handled gracefully.

A commenter raises a good point about users running demanding queries that will swamp the host machine. To mitigate against this, you could try to find a MySQL configuration setting that sets a maximum query time. I couldn't myself find a MySQL setting that would do this, but PostgreSQL offers statement_timeout.

If that is not possible, consider running the query in an AJAX operation in which PHP's maximum execution time is limited to a few seconds. You could consider doing this in SQLite, in order to avoid using a shared database server resource - since in the case of SQLite there is no database server.

Another idea: I believe the SQLFiddle tool uses a strategy of wrapping potentially risky queries in a transaction, fetching the results and then rolling back at the end. That might be worth considering too, though setting the permissions should be sufficient on its own.