-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;
}
C'mon
  • 51
  • 1
  • 10

3 Answers3

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

Community
  • 1
  • 1
Langusten Gustel
  • 10,917
  • 9
  • 46
  • 59
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/

remedy.
  • 2,032
  • 3
  • 25
  • 48
  • 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. ;-) – Funk Forty Niner Feb 04 '14 at 16:22
  • 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) – STT LCU Feb 04 '14 at 16:23
  • @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... :) – Joachim Isaksson Feb 04 '14 at 16:24
  • 1
    @Fred-ii- You did this using regex? – remedy. Feb 04 '14 at 16:27
  • I used `in_array()` @charlesisjan - No regex used. – Funk Forty Niner Feb 04 '14 at 16:36
  • Okay. well maybe I used the word "not possible" incorrectly. What I really meant was that regex isn't what he should be using to check if statements are valid. SQL parser is the answer! – remedy. Feb 04 '14 at 16:40
  • I agree with your last comment. "there is a way, but you shouldn't do it like that but using a SQL parser" is a good answer for me. – STT LCU Feb 05 '14 at 07:33
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

sigy
  • 2,408
  • 1
  • 24
  • 55