I have a Symfony 4 project
and I want to store mysql
queries in as a string in a mysql database
. However, before storing the strings I want to make sure they are valid mysql syntax
. Is there a way of doing this?
Thanks!
-
Have a look at this subject https://stackoverflow.com/questions/21557674/check-if-sql-input-is-valid-sql – Gregoire Ducharme Mar 26 '18 at 09:06
-
1Possible duplicate of [Validating SQL query with PHP](https://stackoverflow.com/questions/1386010/validating-sql-query-with-php) – iksajotien Mar 26 '18 at 09:57
-
Are you looking to store the queries in the same database that you want to check your statement syntax against? – Paul Campbell Mar 26 '18 at 10:12
-
What's the purpose? – axiac Mar 26 '18 at 10:28
2 Answers
I didn't test it but it should work.
Use the database API you already use in your project to prepare the SQL statements you want to validate then discard them; do not execute the prepared statements.
For example, using PDO, use PDO::prepare()
to ask the server to prepare the statement. It returns a PDOStatement
object on success (i.e. when the query is correct). Do not call execute() on the returned statement, just discard it (using unset()
).
PDO::prepare()
returns FALSE
or throws an exception on error, depending on how the PDO's error handling is configured.

- 68,258
- 9
- 99
- 134
The easiest way would be to run a query in a new transaction and then roll it back. SQL can get complex to validate especially if you plan to allow MySQL-specific functions. What if a new function gets introduced in next MySQL release? Writing and maintaining a separate SQL validation library seems counterproductive.
Why not to try following:
Create a new user for running these queries in your database. This will allow you to manage security e.g. allowing only to use
SELECT
statement so no one will runDROP DATABASE
.Run the user provided statement using the new user created in point 1. Start a new transaction using
START TRANSACTION
, execute the user provided statement, and rollback withROLLBACK
. EnsureSET autocommit=0
is set as per 13.3.1 START TRANSACTION, COMMIT, and ROLLBACK Syntax.If the user provided statement executes without errors it's valid. You don't have to read all the returned rows in your PHP code.
Make sure to check on performance because some statements will be expensive to execute. This functionality can DOS your application.
I'd probably create procedure or function in the database. That's what they are for. Storing SQL in a table just to query it and then execute only results in a redundant round trip between the database and the application.

- 43,645
- 9
- 78
- 111