0

How can I use PHP preg_match for a string to check if it contains any sql? Not for preventing SQL injection but just to tell if it contains a sql statement

3
  • You can't. You can look for some SQL specific keywords, but to check if its valid SQL you need some heavier logic. Commented Nov 17, 2014 at 17:58
  • You could try to execute the query and get the return of that execute in a variable. You could set up a test database for these queries so your actual data isn't compromised. Commented Nov 17, 2014 at 18:07
  • 1
    $sql = 's' . 'e' . 'l' . 'e' . 'c' . 't' . 'etc...'. There's a string that contains some SQL...good luck coming up with a regex that could detect every potential variation of that... Commented Nov 17, 2014 at 18:09

1 Answer 1

3

Checking a string for SQL is not worth your time or resources for that matter. If the goal is to prevent injection you should use PDO.

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

Reference material: How can I prevent SQL injection in PHP?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.