-4

Is there any Regular Expression to check if a string is valid SQL? It must be PHP compatible. My code.

if(!preg_match("regular expression", $_POST['sql_input']){
    echo "Please enter valid SQL.";
    exit;
}
7
  • There are many dialects of SQL, any particular one you have in mind? Commented Feb 4, 2014 at 16:19
  • What are you doing to be doing with these posted SQL queries? DELETE FROM users; and DROP DATABASE database are valid queries ;) Commented Feb 4, 2014 at 16:19
  • Maybe this could help: code.google.com/p/php-sql-parser Commented Feb 4, 2014 at 16:20
  • you already asked it yesterday! Commented Feb 4, 2014 at 16:22
  • Why would you need to do this in the first place? Commented Feb 4, 2014 at 16:28

3 Answers 3

0

You could try this library: http://code.google.com/p/php-sql-parser/. I've not used it yet so I can't guarantee it but the code looks like it will be able to tell the difference between valid and invalid SQL.

Another option could be to use transactions if your SQL variant allows it. A transaction would allow you to execute the SQL and then cancel it afterwards reversing any damage that was done. I think I would prefer option 1 though.

I am quoting Godwin. Source

Sign up to request clarification or add additional context in comments.

1 Comment

Re: transactions, most (all?) databases won't allow you to roll back for example DROP DATABASE.
0

No, it is impossible. But if you want to protect yourself against SQL injection attacks, there are other mechanisms you should use.

See for example: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php

Comments

0

Simple answer. What you are trying to do is not possible.

You need an SQL Parser to check if statements are valid.

Check here: http://www.dpriver.com/blog/list-of-demos-illustrate-how-to-use-general-sql-parser/vendor-specific-offline-sql-syntax-check/

7 Comments

Actually, it is possible (with the right sequence of 0's and 1's anything is possible nowadays ;-). I made a script using an array of keywords, and if one was found, then it would do whatever I told it to do. It could easily be modified to suit the OP's wish. Btw, I did NOT downvote this. It's not my style. ;-)
If you want to say that something is not possible, you have to demonstrate it. The other answer(s) disagree with you. (I'm the downvoter)
@STTLCU Well, to be fair I don't see a disagreeing answer that actually shows a regex or any pointer to how to construct an actual regex for doing it either... :)
@Fred-ii- You did this using regex?
I used in_array() @charlesisjan - No regex used.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.